简体   繁体   English

使用Linux检查子进程是否在Linux中运行

[英]Check if a subprocess is running in Linux using Python

I have an environment variable that allows a suite of applications to run under certain conditions, and the applications cannot run with the environment variable off. 我有一个环境变量,它允许一组应用程序在某些条件下运行,并且应用程序无法在环境变量关闭的情况下运行。

My python script uses 我的python脚本使用

p = subprocess.Popen(cmdStr3,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)

to open the subprocess. 打开子流程。

To test if the application is running, I have tried 为了测试应用程序是否正在运行,我尝试了

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

and also checking p.returncode . 并检查p.returncode However, these always return true, because even if the application doesn't pull up on the screen, there are mini processes of ~1 MB that still run without the application fully running, so the os sees these and returns true. 但是,这些总是返回true,因为即使应用程序未在屏幕上弹出,仍有〜1 MB的微型进程仍在运行,而应用程序未完全运行,因此os会看到这些并返回true。 Is there a way around this? 有没有解决的办法?

Another issue is that os.kill doesn't work, the only way I have found to terminate the application is os.killpg at the end. 另一个问题是os.kill不起作用,我发现终止应用程序的唯一方法是os.killpg

What I've learned from the comments is that what actually happens is that the subprocess I call is a starter that calls a child which is another application. 我从评论中学到的是,实际上发生的是我调用的子进程是一个启动程序,该启动程序调用了另一个应用程序的孩子。 My subprocess always runs, but with the environment variable off, the child application does not run. 我的子进程始终运行,但是在关闭环境变量的情况下,子应用程序无法运行。 Is there a way to see if the child is running? 有没有办法查看孩子是否在跑步?

you can use p.poll() to check if the process is still running. 您可以使用p.poll()检查该进程是否仍在运行。

Another issue is that os.kill doesn't work, the only way I have found to terminate the application is os.killpg at the end. 另一个问题是os.kill不起作用,我发现终止应用程序的唯一方法是最后使用os.killpg。

If you want to kill a process launched using subprocess, you can use p.terminate() . 如果要p.terminate()使用子进程启动的进程,可以使用p.terminate()

Finally, if you want to wait until the process child dies, you can use p.wait() . 最后,如果要等到进程子进程死亡后,可以使用p.wait()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM