【问题标题】:Python checking if a fork() process is finishedPython 检查 fork() 进程是否完成
【发布时间】:2012-05-27 21:22:06
【问题描述】:

只是想知道是否有人可以帮助我。我遇到的问题是我 os.fork() 获取几位信息并将它们发送到一个文件,但检查 fork 进程是否不起作用。

import sys
import time
import os
import re


ADDRESS  = argv[1]
sendBytes = argv[2]


proID2 = os.fork()
if proID2 == 0:
    os.system('ping -c 20 ' + ADDRESS + ' > testStuff2.txt')
    os._exit(0)

print proID2

finn = True
while finn == True:
time.sleep(1)
finn = os.path.exists("/proc/" + str(proID2))
print os.path.exists("/proc/" + str(proID2))
print 'eeup out of it ' + str(proID2)

我认为 os.path.exists() 可能不适合使用。

谢谢。

【问题讨论】:

  • 检查 /proc/###/ 的存在不是好的解决方案。没有定义 PID 如何成为问题。在您的孩子终止后,下一个进程开始(可能完全独立于您的应用程序)可以获得相同的 PID。通常,它们是在周转中发布的,因此使用当前内核,您的解决方案很可能一直有效,但您无法确定未来的内核版本或在特殊情况下,例如当您将计算机置于睡眠模式时,或者您的由于网络延迟、服务器无响应或类似情况,应用程序停滞了很长一段时间。

标签: python fork


【解决方案1】:

虽然您可以使用os.fork()os.wait()(请参阅下面的示例),但您最好使用subprocess 模块中的方法。

import os, sys

child_pid = os.fork()
if child_pid == 0:
    # child process
    os.system('ping -c 20 www.google.com >/tmp/ping.out')
    sys.exit(0)

print "In the parent, child pid is %d" % child_pid
#pid, status = os.wait()
pid, status = os.waitpid(child_pid, 0)
print "wait returned, pid = %d, status = %d" % (pid, status)

【讨论】:

    【解决方案2】:

    要等待子进程终止,请使用os.waitXXX() 函数之一,例如os.waitpid()。这种方法可靠;作为奖励,它会为您提供状态信息。

    【讨论】:

      猜你喜欢
      • 2021-11-08
      • 2021-07-28
      • 2012-09-14
      • 2021-07-13
      • 2012-04-03
      • 2019-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多