]> SALOME platform Git repositories - modules/kernel.git/commitdiff
Salome HOME
CCAR: change tabs to spaces
authorcaremoli <caremoli>
Tue, 25 Sep 2007 12:02:24 +0000 (12:02 +0000)
committercaremoli <caremoli>
Tue, 25 Sep 2007 12:02:24 +0000 (12:02 +0000)
replace launching servers through os.spawn by method daemonize (servers are real daemons now
and are detached from terminal)

bin/addToKillList.py
bin/killSalomeWithPort.py
bin/nameserver.py
bin/orbmodule.py
bin/runNS.py
bin/runSalome.py
bin/server.py
bin/setenv.py

index f29cccef74667767068d50a23075504f225ac733..537dfaf3d8cfb9c1af36ff67772606ed2e6cc1a4 100755 (executable)
@@ -64,8 +64,8 @@ def addToKillList(command_pid, command):
         if verbose(): print process_id
         for pid, cmd in process_id.items():
             #print "see process %s : %s"% (pid, cmd[0])
-           if pid == command_pid:
-               already_in=1
+            if pid == command_pid:
+                already_in=1
                 pass
             pass
         pass
@@ -73,14 +73,14 @@ def addToKillList(command_pid, command):
     command=(command.split(" "))[0]
     if already_in == 0:
         try:
-           process_ids.append({command_pid: [command]})
-           fpid=open(filedict,'w')
+            process_ids.append({command_pid: [command]})
+            fpid=open(filedict,'w')
             pickle.dump(process_ids, fpid)
-           fpid.close()
+            fpid.close()
         except:
-           print "addToKillList: can not add command %s to the kill list"% filedict
-           pass
-       pass
+            print "addToKillList: can not add command %s to the kill list"% filedict
+            pass
+        pass
     pass
 
 def killList():
index 86d112af8157cb72d49e7171a9f44992cd5ba909..79c1682792d42d757f063f757cf8d56a5cab6cd8 100755 (executable)
@@ -102,10 +102,10 @@ def killMyPort(port):
                         if pidfield != "egrep" :
                             if sys.platform == "win32":
                                 import win32pm
-                               print 'stop process '+pidfield+' : omniNames'
+                                print 'stop process '+pidfield+' : omniNames'
                                 win32pm.killpid(int(pidfield),0)
                             else:
-                               if verbose(): print 'stop process '+pidfield+' : omniNames'
+                                if verbose(): print 'stop process '+pidfield+' : omniNames'
                                 os.system('kill -9 '+pidfield)
                     pidfield = field
         except:
@@ -138,7 +138,7 @@ def killMyPort(port):
         while pid != "" and len(a.split(" ")) < 2:
             a = commands.getoutput("pid=`ps -eo pid,command | egrep \"[0-9] omniNames -start "+str(port)+"\" | sed -e \"s%[^0-9]*\([0-9]*\) .*%\\1%g\"`; kill -9 $pid")
             pid = commands.getoutput("ps -eo pid,command | egrep \"[0-9] omniNames -start "+str(port)+"\" | sed -e \"s%[^0-9]*\([0-9]*\) .*%\\1%g\"")
-           print pid
+            print pid
             
         pass
 
index aacb59ed9bdb52be8c255033e0f0e2a89cdd613e..dd03c51a39754a4c38ef680622d51b0db76f3e4f 100755 (executable)
@@ -22,68 +22,67 @@ class NamingServer(Server):
           os.environ["BaseDir"]=os.environ["HOME"]
         else:
           os.environ["BaseDir"]="/tmp"
-     
-       try:
-         os.mkdir(os.environ["BaseDir"] + "/logs")
+
+        try:
+          os.mkdir(os.environ["BaseDir"] + "/logs")
           os.chmod(os.environ["BaseDir"] + "/logs", 0777)
-       except:
-         #print "Can't create " + os.environ["BaseDir"] + "/logs"
-         pass
-       
-       upath = os.environ["BaseDir"] + "/logs/";
-       if sys.platform == "win32":
-          upath += os.environ["Username"];
-       else:
-          upath += os.environ["USER"];
-
-       try:
-         os.mkdir(upath)
-       except:
-         #print "Can't create " + upath
-         pass
-
-       #os.system("touch " + upath + "/dummy")
-       for fname in os.listdir(upath):
-         try:
-           os.remove(upath + "/" + fname)
-         except:
-           pass
-       #os.system("rm -f " + upath + "/omninames* " + upath + "/dummy " + upath + "/*.log")
-
-       print "Name Service... "
-       #hname=os.environ["HOST"] #commands.getoutput("hostname")
+        except:
+          #print "Can't create " + os.environ["BaseDir"] + "/logs"
+          pass
+
+        upath = os.environ["BaseDir"] + "/logs/";
         if sys.platform == "win32":
-           hname=getShortHostName();
+           upath += os.environ["Username"];
         else:
-           hname = socket.gethostname();
-        
-       print "hname=",hname
-       
-       f=open(os.environ["OMNIORB_CONFIG"])
-       ss=re.findall("NameService=corbaname::" + hname + ":\d+", f.read())
-       print "ss = ", ss
-       f.close()
+           upath += os.environ["USER"];
+
+        try:
+          os.mkdir(upath)
+        except:
+          #print "Can't create " + upath
+          pass
+
+        #os.system("touch " + upath + "/dummy")
+        for fname in os.listdir(upath):
+          try:
+            os.remove(upath + "/" + fname)
+          except:
+            pass
+        #os.system("rm -f " + upath + "/omninames* " + upath + "/dummy " + upath + "/*.log")
+
+        print "Name Service... ",
+        #hname=os.environ["HOST"] #commands.getoutput("hostname")
+        if sys.platform == "win32":
+          hname=getShortHostName();
+        else:
+          hname = socket.gethostname();
+        #print "hname=",hname
+
+        f=open(os.environ["OMNIORB_CONFIG"])
+        ss=re.findall("NameService=corbaname::" + hname + ":\d+", f.read())
+        print "ss = ", ss,
+        f.close()
         sl=ss[0]
         ll = sl.split(':')
         aPort = ll[-1]
         #aPort=(ss.join().split(':'))[2];
-       #aPort=re.findall("\d+", ss[0])[0]
-       
-       #aSedCommand="s/.*NameService=corbaname::" + hname + ":\([[:digit:]]*\)/\1/"
-       #print "sed command = ", aSedCommand
-       #aPort = commands.getoutput("sed -e\"" + aSedCommand + "\"" + os.environ["OMNIORB_CONFIG"])
-       print "port=", aPort
-       if sys.platform == "win32":
-         #print "start omniNames -start " + aPort + " -logdir " + upath
+        #aPort=re.findall("\d+", ss[0])[0]
+
+        #aSedCommand="s/.*NameService=corbaname::" + hname + ":\([[:digit:]]*\)/\1/"
+        #print "sed command = ", aSedCommand
+        #aPort = commands.getoutput("sed -e\"" + aSedCommand + "\"" + os.environ["OMNIORB_CONFIG"])
+        #print "port=", aPort
+        if sys.platform == "win32":
+          #print "start omniNames -start " + aPort + " -logdir " + upath
           self.CMD=['omniNames -start ' , aPort , ' -logdir ' , '\"' + upath + '\"']
-         #os.system("start omniNames -start " + aPort + " -logdir " + upath)
-       else:
+          #os.system("start omniNames -start " + aPort + " -logdir " + upath)
+        else:
           #self.CMD=['omniNames -start ' , aPort , ' -logdir ' , upath , ' &']
           self.CMD=['omniNames','-start' , aPort, '-logdir' , upath ]
-         #os.system("omniNames -start " + aPort + " -logdir " + upath + " &")
+          #os.system("omniNames -start " + aPort + " -logdir " + upath + " &")
 
-       print "ok"
-       print "to list contexts and objects bound int the context with the specified name : showNS "
+        print "... ok"
+        print "to list contexts and objects bound into the context with the specified name : showNS "
 
 
    def initArgs(self):
@@ -95,7 +94,6 @@ class NamingServer(Server):
         self.CMD=['xterm', '-e']+ env_ld_library_path + ['python']
         self.initNSArgs()
 
-        
 # In LifeCycleCORBA, FactoryServer is started with rsh on the requested
 #    computer if this Container does not exist. Default is localhost.
 #    Others Containers are started with start_impl method of FactoryServer Container.
index 86c89201e97674aa142cc5a915501db9bdbd459d..f629aa847bdea4c4316cff5db044d8eb78dec245 100755 (executable)
@@ -35,14 +35,11 @@ class client:
       # Initialise the ORB
       self.orb=CORBA.ORB_init(sys.argv, CORBA.ORB_ID)
       # Initialise the Naming Service
-      print "Obtain a reference to the root naming context"
-      print args 
       self.initNS(args)
 
    # --------------------------------------------------------------------------
 
    def initNS(self,args):
-      print "Obtain a reference to the root naming context"
       # Obtain a reference to the root naming context
       obj         = self.orb.resolve_initial_references("NameService")
       try:
@@ -50,7 +47,7 @@ class client:
           return
       except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE):
           self.rootContext = None
-          print "Lancement du Naming Service",
+          print "Launch Naming Service++",
           
       # On lance le Naming Server (doit etre dans le PATH)
       NamingServer(args).run()
@@ -151,9 +148,9 @@ class client:
       print "Searching %s in Naming Service " % theName,
       while(1):
          try:
-            aPid, aStatus = os.waitpid(thePID,os.WNOHANG)
-         except Exception, exc:
-            raise "Impossible de trouver %s" % theName
+           os.kill(thePID,0)
+         except:
+           raise "Process %d for %s not found" % (thePID,theName)
          aCount += 1
          anObj = self.Resolve(theName)
          if anObj: 
index 5af2c5af5b31f4ec5cd475787f0873b0f0fe350f..44476036965a6c885b9f56b0eb61bc4399b908dc 100755 (executable)
@@ -6,11 +6,11 @@ import os, commands, sys, re, string, socket
 from Utils_Identity import getShortHostName
 
 if sys.platform == "win32":
-       # temporarily using home directory for Namning Service logs
-       # to be replaced with TEMP later...
-       os.environ["BaseDir"]=os.environ["HOME"]
+  # temporarily using home directory for Namning Service logs
+  # to be replaced with TEMP later...
+  os.environ["BaseDir"]=os.environ["HOME"]
 else:
-       os.environ["BaseDir"]="/tmp"
+  os.environ["BaseDir"]="/tmp"
 
 os.environ["Username"]=os.environ["USER"]
 
@@ -21,50 +21,50 @@ os.environ["Username"]=os.environ["USER"]
 # clear log files
 
 def startOmni():
-       try:
-         os.mkdir(os.environ["BaseDir"] + "/logs")
-          os.chmod(os.environ["BaseDir"] + "/logs", 0777)
-       except:
-         #print "Can't create " + os.environ["BaseDir"] + "/logs"
-         pass
-       
-       upath = os.environ["BaseDir"] + "/logs/" + os.environ["Username"]
-
-       try:
-         os.mkdir(upath)
-       except:
-         #print "Can't create " + upath
-         pass
-
-       #os.system("touch " + upath + "/dummy")
-       for fname in os.listdir(upath):
-         try:
-           os.remove(upath + "/" + fname)
-         except:
-           pass
-       #os.system("rm -f " + upath + "/omninames* " + upath + "/dummy " + upath + "/*.log")
-
-       print "Name Service... "
-       #hname=os.environ["HOST"] #commands.getoutput("hostname")
-       if sys.platform == "win32":
+  try:
+    os.mkdir(os.environ["BaseDir"] + "/logs")
+    os.chmod(os.environ["BaseDir"] + "/logs", 0777)
+  except:
+    #print "Can't create " + os.environ["BaseDir"] + "/logs"
+    pass
+  
+  upath = os.environ["BaseDir"] + "/logs/" + os.environ["Username"]
+
+  try:
+    os.mkdir(upath)
+  except:
+    #print "Can't create " + upath
+    pass
+
+  #os.system("touch " + upath + "/dummy")
+  for fname in os.listdir(upath):
+    try:
+      os.remove(upath + "/" + fname)
+    except:
+      pass
+  #os.system("rm -f " + upath + "/omninames* " + upath + "/dummy " + upath + "/*.log")
+
+  print "Name Service... "
+  #hname=os.environ["HOST"] #commands.getoutput("hostname")
+  if sys.platform == "win32":
           hname=getShortHostName()
-       else:
-         hname=socket.gethostname()
-
-       print "hname=",hname
-       
-       f=open(os.environ["OMNIORB_CONFIG"])
-       ss=re.findall("NameService=corbaname::" + hname + ":\d+", f.read())
-       print "ss = ", ss
-       f.close()
-       aPort=re.findall("\d+", ss[0])[0]
-       
-       #aSedCommand="s/.*NameService=corbaname::" + hname + ":\([[:digit:]]*\)/\1/"
-       #print "sed command = ", aSedCommand
-       #aPort = commands.getoutput("sed -e\"" + aSedCommand + "\"" + os.environ["OMNIORB_CONFIG"])
-        global process_id
-       print "port=", aPort
-       if sys.platform == "win32":          
+  else:
+    hname=socket.gethostname()
+
+  print "hname=",hname
+  
+  f=open(os.environ["OMNIORB_CONFIG"])
+  ss=re.findall("NameService=corbaname::" + hname + ":\d+", f.read())
+  print "ss = ", ss
+  f.close()
+  aPort=re.findall("\d+", ss[0])[0]
+  
+  #aSedCommand="s/.*NameService=corbaname::" + hname + ":\([[:digit:]]*\)/\1/"
+  #print "sed command = ", aSedCommand
+  #aPort = commands.getoutput("sed -e\"" + aSedCommand + "\"" + os.environ["OMNIORB_CONFIG"])
+  global process_id
+  print "port=", aPort
+  if sys.platform == "win32":          
           #import win32pm
           #command = ['omniNames -start ' , aPort , ' -logdir ' , '\"' + upath + '\"']
           #os.system("start omniNames -start " + aPort + " -logdir " + "\"" + upath + "\"" )
@@ -72,11 +72,11 @@ def startOmni():
           #print command
           pid = win32pm.spawnpid( string.join(command, " "), -nc )
           process_id[pid]=command
-       else:
-         os.system("omniNames -start " + aPort + " -logdir " + upath + " &")
+  else:
+    os.system("omniNames -start " + aPort + " -logdir " + upath + " &")
 
-       print "ok"
-       print "to list contexts and objects bound int the context with the specified name : showNS "
+  print "ok"
+  print "to list contexts and objects bound into the context with the specified name : showNS "
 
 # In LifeCycleCORBA, FactoryServer is started with rsh on the requested
 #    computer if this Container does not exist. Default is localhost.
index 69f974aff69b9de766694a7b01ac6c6cf9237e8d..30b84ff1692a136ccf43f0bb6875f903d0b9ef41 100755 (executable)
@@ -88,10 +88,10 @@ class InterpServer(Server):
         global process_id
         command = self.CMD
         print "INTERPSERVER::command = ", command
-       if sys.platform == "win32":
+        if sys.platform == "win32":
           import win32pm
           pid = win32pm.spawnpid( string.join(command, " "),'-nc' )
-       else:
+        else:
           pid = os.spawnvp(os.P_NOWAIT, command[0], command)
         process_id[pid]=self.CMD
         self.PID = pid
@@ -102,9 +102,9 @@ class CatalogServer(Server):
     def __init__(self,args):
         self.args=args
         self.initArgs()
-       #if sys.platform == "win32":
-  #        self.SCMD1=[os.environ["KERNEL_ROOT_DIR"] + "/win32/" + os.environ["BIN_ENV"] + "/" + 'SALOME_ModuleCatalog_Server' + ".exe",'-common']
-       #else:
+        #if sys.platform == "win32":
+        #        self.SCMD1=[os.environ["KERNEL_ROOT_DIR"] + "/win32/" + os.environ["BIN_ENV"] + "/" + 'SALOME_ModuleCatalog_Server' + ".exe",'-common']
+        #else:
         self.SCMD1=['SALOME_ModuleCatalog_Server','-common']
         self.SCMD2=[]
         home_dir=os.getenv('HOME')
@@ -182,9 +182,9 @@ class ContainerPYServer(Server):
     def __init__(self,args):
         self.args=args
         self.initArgs()
-       if sys.platform == "win32":
+        if sys.platform == "win32":
           self.CMD=[os.environ["PYTHONBIN"], '\"'+os.environ["KERNEL_ROOT_DIR"] + '/bin/salome/SALOME_ContainerPy.py'+'\"','FactoryServerPy']
-       else:
+        else:
           self.CMD=['SALOME_ContainerPy.py','FactoryServerPy']
 
 # ---
@@ -193,9 +193,9 @@ class ContainerSUPERVServer(Server):
     def __init__(self,args):
         self.args=args
         self.initArgs()
-#      if sys.platform == "win32":
+   #  if sys.platform == "win32":
 #          self.CMD=[os.environ["KERNEL_ROOT_DIR"] + "/win32/" + os.environ["BIN_ENV"] + "/" + 'SALOME_Container' + ".exe",'SuperVisionContainer']
-#      else:
+# else:
         self.CMD=['SALOME_Container','SuperVisionContainer']
 
 # ---
@@ -215,11 +215,10 @@ class SessionServer(Server):
     def __init__(self,args):
         self.args = args.copy()
         # Bug 11512 (Problems with runSalome --xterm on Mandrake and Debian Sarge)
-        self.args['xterm']=0
+        #self.args['xterm']=0
         #
         self.initArgs()
         self.SCMD1=['SALOME_Session_Server']
-       
         self.SCMD2=[]
         if 'registry' in self.args['embedded']:
             self.SCMD1+=['--with','Registry',
@@ -707,11 +706,11 @@ def searchFreePort(args, save_config=1):
             print "%s - OK"%(NSPORT)
             #
             from os import getpid
-           if sys.platform == "win32":
-               tmp_file = os.getenv('TEMP');
+            if sys.platform == "win32":
+                tmp_file = os.getenv('TEMP');
             else:
                 tmp_file = '/tmp/'
-           tmp_file += 'hostname_%s'%(getpid())
+            tmp_file += 'hostname_%s'%(getpid())
             #tmp_file = '/tmp/hostname_%s'%(getpid())
             from os import system
             system('hostname > %s'%(tmp_file))
index 88e74720e3bfec12af99a3d62d04d5faf5513246..4c3554572dd0faab50a565e53784a809a14f2700 100755 (executable)
@@ -14,7 +14,7 @@ class Server:
     def initArgs(self):
         self.PID=None
         self.CMD=[]
-        self.ARGS=[]   
+        self.ARGS=[]
         if self.args['xterm']:
             self.ARGS=['xterm', '-iconic', '-sb', '-sl', '500', '-hold']
 
@@ -32,15 +32,61 @@ class Server:
                                  + os.getenv("LD_LIBRARY_PATH")]
             myargs = myargs +['-T']+self.CMD[:1]+['-e'] + env_ld_library_path
         command = myargs + self.CMD
-        print "command = ", command
-       if sys.platform == "win32":
+        #print "command = ", command
+        if sys.platform == "win32":
           import win32pm
           #cmd_str = "\"" + string.join(command, " ") + "\""
           #print cmd_str
           #pid = win32pm.spawnpid( cmd_str )
           pid = win32pm.spawnpid( string.join(command, " "), '-nc' )
           #pid = win32pm.spawnpid( string.join(command, " ") )
-       else:
-          pid = os.spawnvp(os.P_NOWAIT, command[0], command)
+        else:
+          #pid = os.spawnvp(os.P_NOWAIT, command[0], command)
+          pid=self.daemonize(command)
         process_id[pid]=self.CMD
         self.PID = pid
+        return pid
+
+    def daemonize(self,args):
+        # to daemonize a process need to do the UNIX double-fork magic
+        # see Stevens, "Advanced Programming in the UNIX Environment" for details (ISBN 0201563177)
+        # and UNIX Programming FAQ 1.7 How do I get my program to act like a daemon?
+        #     http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
+        #open a pipe
+        c2pread, c2pwrite = os.pipe()
+        #do first fork
+        pid=os.fork()
+        if pid > 0:
+          #first parent
+          os.close(c2pwrite)
+          #receive real pid from child
+          data=os.read(c2pread,24) #read 24 bytes
+          os.waitpid(pid,0) #remove zombie
+          os.close(c2pread)
+          # return : first parent
+          return int(data)
+
+        #first child
+        # decouple from parent environment
+        os.setsid()
+        os.close(c2pread)
+
+        # do second fork : second child not a session leader
+        try:
+          pid = os.fork()
+          if pid > 0:
+            #send real pid to parent
+            os.write(c2pwrite,"%d" % pid)
+            os.close(c2pwrite)
+            # exit from second parent
+            os._exit(0)
+        except OSError, e:
+          print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror)
+          os.write(c2pwrite,"-1")
+          os.close(c2pwrite)
+          sys.exit(1)
+
+        #I am a daemon
+        os.close(0) #close stdin
+        os.open("/dev/null", os.O_RDWR)  # redirect standard input (0) to /dev/null
+        os.execvp(args[0], args)
index b401b37099c32b1fab83b404659ed9d9eae5ad23..81b81942691a2488604d6048d1ef9e962dcda54e 100755 (executable)
@@ -37,9 +37,9 @@ salome_subdir = "salome"
 def add_path(directory, variable_name):
     """Function helper to add environment variables"""
     if sys.platform == "win32":
-         splitsym = ";"
+      splitsym = ";"
     else:
-         splitsym = ":"
+      splitsym = ":"
     if not os.environ.has_key(variable_name):
         os.environ[variable_name] = ""
         pass
@@ -240,9 +240,9 @@ def set_env(args, modules_list, modules_root_dir):
                              "PYTHONPATH")
 
 
-                   if sys.platform == "win32":
-                     add_path(os.path.join(plugin_root,get_lib_dir(),salome_subdir),
-                               "PATH")
+                    if sys.platform == "win32":
+                      add_path(os.path.join(plugin_root,get_lib_dir(),salome_subdir),
+                          "PATH")
                     else:
                       add_path(os.path.join(plugin_root,get_lib_dir(),salome_subdir),
                                "LD_LIBRARY_PATH")