使用 pid 轮询子进程

Polling a subprocess using pid

我有一个 Django 项目,允许用户一次启动多个子进程。这些过程可能需要一些时间,因此用户可以继续使用应用程序的其他方面。在任何情况下,用户都可以查看所有 运行 进程并轮询其中任何一个以检查其是否结束。为此,我需要使用它的 pid 来轮询进程。 Popen.poll() 需要一个 subprocess.Peopen 对象,而我所拥有的只是该对象的 pid。我怎样才能得到想要的结果?

在models.py中:

class Runningprocess(models.Model):
    #some other fields
    p_id=models.CharField(max_length=500)
    def __str__(self):
        return self.field1

在views.py中:

def run_process():
    ....
    p= subprocess.Popen(cmd, shell =True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    new_p=Runningprocess()  
    new_p.p_id=p.pid
    ....
    new_p.save()
    return HttpResponseRedirect('/home/')   

def check(request,pid):
    #here i want to be able to poll the subprocess using the p_id e.g something like:
     checkp = pid.poll() #this statement is wrong
     if checkp is None:
           do something
     else:
           do something else

我只需要一个有效的声明而不是 'checkp = pid.poll()'

不要使用 PID 轮询

PID 是分配给进程的临时 ID。只要进程是 运行,它就会留在进程中。当一个进程终止或被杀死时,它的 PID 可能(或可能不会立即)分配给其他一些进程。因此,现在有效的进程 PID 可能在一段时间后不再有效。

现在,如何轮询进程?

这是我在我的一个项目中所做的:

psub = subprocess.Popen(something)
# polling

while psub.poll() is None:
    pass

但请注意,上述代码可能会导致死锁。为避免死锁,您可以使用两种方法:

  1. 使用计数器。当计数器值变得大于某个固定值时 - 终止进程。

2.Use 超时。获取进程启动的开始时间以及进程花费的时间超过固定时间的时间 - 终止。

start_time = time.time()
timeout = 60 # 60 seconds
while psub.poll() is None:
    if time.time() - start_tym >= int(timeout):
        psub.kill()