我希望通过函数subprocess.call()启动子进程,并且我希望主循环等待直到子进程启动。
我想使用线程。锁:
- 在subprocess.call() 之前获取它
- 然后试图重新获取它(所以它等待)
- 和在subprocess.call()(主循环未锁定) 后释放
子进程必须作为守护进程运行,所以我将subprocess.call()放在线程中。
但是它在subprocess.call()之后停止,我认为它只是在等待,因为pyr -ns是一个监听端口的守护进程。我怎样才能做到这一点呢?
看代码,更简单:
self.__wait_pyroNS_lock=threading.Lock()
self.__logger.debug('i get wait_pyroNS_lock')
self.__wait_pyroNS_lock.acquire()
pyro_ns = threading.Thread(name='Pyro Name Server', target=self.__Pyro_NameServer, args=(self.__wait_pyroNS_lock,))
pyro_ns.setDaemon(True)
self.__logger.debug('starting thread def self.__Pyro_NameServer')
pyro_ns.start()
self.__wait_pyroNS_lock.acquire() # <--- MAIN LOOP WAITING HERE
self.__wait_pyroNS_lock.release()
def __Pyro_NameServer(self, wait_pyroNS_lock):
try:
self.__logger.debug('def __Pyro_NameServer')
self.__logger.debug('starting pyro-ns')
retcode = subprocess.call("pyro-ns", shell=True) # <--- THREAD STOPS HERE, it doesn't return, so i don't get any code and it's all locked.
if retcode != 0:
self.__logger.debug('command pyro-ns: fail, error code %d' % retcode)
else:
self.__logger.debug('pyro-ns has started')
self.__logger.debug('releasing wait_pyroNS_lock')
wait_pyroNS_lock.release() # <--- IT NEVER RUNS, it releases the lock, the main loop is unlocked
except Exception as e:
self.__logger.error('%s' % str(e))
我决定使用PyRO提供的API。
pyro_ns_object = Pyro.naming.NameServerStarter()
pyro_ns = threading.Thread(name='Pyro Name Server', target=self.__Pyro_NameServer, args=(pyro_ns_object,))
pyro_ns.setDaemon(True)
self.__logger.debug('start thread def self.__Pyro_NameServer')
pyro_ns.start()
while True:
if pyro_ns_object.waitUntilStarted(timeout=0.1):
break
else:
self.__logger.debug('waiting pyro-ns')
def __Pyro_NameServer(self, pyro_ns_object):
try:
self.__logger.debug('def __Pyro_NameServer')
self.__logger.debug('starting pyro-ns')
pyro_ns_object.start()
except Exception as e:
self.__logger.error('%s' % str(e))
raise e