有没有办法检查pid是否对应一个有效的进程?我从不同的来源获得了一个pidos.getpid(),我需要检查是否在该机器上不存在具有该pid的进程.
我需要它在Unix和Windows中可用.我还在检查PID是否未被使用.
我试图atexit在一个Process,但不幸的是它似乎没有用.这是一些示例代码:
import time
import atexit
import logging
import multiprocessing
logging.basicConfig(level=logging.DEBUG)
class W(multiprocessing.Process):
def run(self):
logging.debug("%s Started" % self.name)
@atexit.register
def log_terminate():
# ever called?
logging.debug("%s Terminated!" % self.name)
while True:
time.sleep(10)
@atexit.register
def log_exit():
logging.debug("Main process terminated")
logging.debug("Main process started")
a = W()
b = W()
a.start()
b.start()
time.sleep(1)
a.terminate()
b.terminate()
Run Code Online (Sandbox Code Playgroud)
此代码的输出是:
DEBUG:root:Main process started DEBUG:root:W-1 Started DEBUG:root:W-2 Started DEBUG:root:Main process terminated
我希望的是,W.run.log_terminate()将被调用时a.terminate()和b.terminate()被调用,并且输出被什么东西likeso(强调)!:
DEBUG:root:Main process started DEBUG:root:W-1 Started DEBUG:root:W-2 Started …