简体   繁体   中英

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

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

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.

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.

If you want to kill a process launched using subprocess, you can use p.terminate() .

Finally, if you want to wait until the process child dies, you can use p.wait() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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