等待直到某个过程(知道"pid")结束 [英] Wait until a certain process (knowing the "pid") end

查看:78
本文介绍了等待直到某个过程(知道"pid")结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个:

def get_process():
    pids = []
    process = None
    for i in os.listdir('/proc'):
        if i.isdigit():
            pids.append(i)

    for pid in pids:
        proc = open(os.path.join('/proc', pid, 'cmdline'), 'r').readline()
        if proc == "Something":
            process = pid

    return process          

def is_running(pid):
    return os.path.exists("/proc/%s" % str(pid))

然后我这样做:

process = get_process()
if process == None:
    #do something
else:
    #Wait until the process end
    while is_running(process):
        pass

我认为这不是等待进程终止的最佳方法,必须有一些函数等待之类的东西,但是我找不到它.

I think this is not the best way to wait for the process to terminate, there must be some function wait or something, but i can't find it.

免责声明:该进程不是子进程

Disclaimer: The process is not a child process

推荐答案

我并不是真正的Python程序员,但显然Python确实具有

I'm not really a Python programmer, but apparently Python does have os.waitpid(). That should consume less CPU time and provide a much faster response than, say, trying to kill the process at quarter-second intervals.

附录:正如Niko所指出的,如果该进程不是当前进程的子进程,则os.waitpid()可能不起作用.在那种情况下,使用os.kill(pid, 0)可能确实是最好的解决方案.请注意,通常,在流程上调用os.kill()有三种可能的结果:

Addendum: As Niko points out, os.waitpid() may not work if the process is not a child of the current process. In that case, using os.kill(pid, 0) may indeed be the best solution. Note that, in general, there are three likely outcomes of calling os.kill() on a process:

  1. 如果该进程存在并属于您,则调用成功.
  2. 如果该进程存在但属于另一个用户,它将抛出一个OSError,其errno属性设置为 errno.ESRCH .
  1. If the process exists and belongs to you, the call succeeds.
  2. If the process exists but belong to another user, it throws an OSError with the errno attribute set to errno.EPERM.
  3. If the process does not exist, it throws an OSError with the errno attribute set to errno.ESRCH.

因此,要可靠地检查某个进程是否存在,您应该执行类似的操作

Thus, to reliably check whether a process exists, you should do something like

def is_running(pid):        
    try:
        os.kill(pid, 0)
    except OSError as err:
        if err.errno == errno.ESRCH:
            return False
    return True

这篇关于等待直到某个过程(知道"pid")结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆