我正在研究一个漂亮的小功能:
def startProcess(name, path):
"""
Starts a process in the background and writes a PID file
returns integer: pid
"""
# Check if the process is already running
status, pid = processStatus(name)
if status == RUNNING:
raise AlreadyStartedError(pid)
# Start process
process = subprocess.Popen(path + ' > /dev/null 2> /dev/null &', shell=True)
# Write PID file
pidfilename = os.path.join(PIDPATH, name + '.pid')
pidfile = open(pidfilename, 'w')
pidfile.write(str(process.pid))
pidfile.close()
return process.pid
问题是 process.pid
isn 't the correct PID. It seems it'总是比正确的PID低1 . 例如,它表示该过程始于31729,但 ps
表示's running at 31730. Every time I'已经尝试过's off by 1. I'猜测它返回的PID是 current 进程的PID,而不是已启动的PID,并且新进程获得'next' pid为1更高 . 如果是这种情况,我不能仅仅依赖于返回 process.pid + 1
,因为我无法保证它始终是正确的 .
为什么 process.pid
不返回新进程的PID,我怎样才能实现我之后的行为?
1 回答
从http://docs.python.org/library/subprocess.html的文档:
如果
shell
为假,我认为应该按照您的预期行事 .