我工作的一個漂亮的小功能:打開與POPEN的過程和獲取PID
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
不正確的PID。看起來總是比正確的PID低1。例如,它說,這個過程開始於31729,但ps
說,它運行在31730.每次我試了一下功能是關閉的1。我猜它返回的PID是當前進程的PID,而不是時間開始一個,新的過程獲得'下一個'pid,這是更高的1。如果是這樣,我不能僅僅依靠返回process.pid + 1
,因爲我不能保證它總是正確的。
爲什麼不process.pid
返回PID的新進程,我如何能實現我以後的行爲嗎?
嘗試刪除'shell = True'和你的'''東西。 – Blender
我有同樣的問題,我發現困難的方式,它並不總是PID + 1,這是第一次,但現在它給了我+2 – andrei