Linux 等到某个进程(知道“pid”)结束

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7653178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 06:30:10  来源:igfitidea点击:

Wait until a certain process (knowing the "pid") end

pythonlinuxprocesswaitpid

提问by Niko

I have this:

我有这个:

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))

Then i do this:

然后我这样做:

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

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

采纳答案by Ilmari Karonen

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.

我不是真正的 Python 程序员,但显然 Python 确实有os.waitpid(). 与尝试以四分之一秒的间隔终止进程相比,这应该消耗更少的 CPU 时间并提供更快的响应。



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:

附录:正如 Niko 所指出的,os.waitpid()如果进程不是当前进程的子进程,则可能无法工作。在这种情况下,使用os.kill(pid, 0)可能确实是最好的解决方案。请注意,一般来说,调用os.kill()进程有三种可能的结果:

  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 OSErrorwith the errnoattribute set to errno.EPERM.
  3. If the process does not exist, it throws an OSErrorwith the errnoattribute set to errno.ESRCH.
  1. 如果该进程存在并且属于您,则调用成功。
  2. 如果进程存在,但属于另一个用户时,它抛出一个OSErrorerrno属性设置为errno.EPERM
  3. 如果进程不存在,它抛出一个OSErrorerrno属性设置为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

回答by chown

import time, then use time.sleep(#):

import time,然后使用time.sleep(#)

import time
process = get_process()
if process == None:
? ? #do something
else:
? ? #Wait until the process end
? ? while is_running(process):
? ? ? ? time.sleep(0.25)

I also have that exact same function in several of my scrips to read through /proc/#/cmdlineto check for a PID.

我在我的几个脚本中也有完全相同的功能来通读/proc/#/cmdline以检查 PID。

回答by jdi

Since that method would only work on linux, for linux/osx support, you could do:

由于该方法仅适用于 linux,对于 linux/osx 支持,您可以执行以下操作:

import time
import os

def is_running(pid):
    stat = os.system("ps -p %s &> /dev/null" % pid)
    return stat == 0

pid = 64463

while is_running(pid):
    time.sleep(.25)

Edit- Per tMc's comment about excessive processes

编辑- 根据 tMc 关于过度流程的评论

Referencing: How to check if there exists a process with a given pid in Python?

参考: 如何检查 Python 中是否存在具有给定 pid 的进程?

Wouldn't this use less resources (I havent tested), than listing on the filesystem and opening FDs to all the results?

这会不会比在文件系统上列出并打开 FD 以获得所有结果使用更少的资源(我还没有测试过)?

import time
import os

def is_running(pid):        
    try:
        os.kill(pid, 0)
    except OSError:
        return False

    return True

pid = 64463

while is_running(pid):
    time.sleep(.25)

回答by FallenSpaces

A simple and reliable way of doing this with Python is by getting a list of PIDs with psutil, and then checking if your PID is in that list of running PIDs:

使用 Python 执行此操作的一种简单而可靠的方法是使用 psutil 获取 PID 列表,然后检查您的 PID 是否在该正在运行的 PID 列表中:

import psutil

def check_pid(pid):

    if int(pid) in psutil.pids(): ## Check list of PIDs
        return True ## Running
    else:
        return False ## Not Running

To use it, just run it in a simple while loop.

要使用它,只需在一个简单的 while 循环中运行它。

pid = 1000
running = True

while running == True:
    running = check_pid(int(pid))
    (Do stuff *until* PID ends)

(Do stuff *after* PID ends)


Or you could just put all that into one function...

或者你可以把所有这些都放在一个函数中......

def pause_while_running(pid):

    running = True

    while running:
        if int(pid) not in psutil.pids():
            running = False
        time.sleep(5)

and use like

并使用像

pause_while_running(pid)
(do stuff after PID ended)