user3632833
user3632833

Reputation: 81

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?

Upvotes: 2

Views: 12291

Answers (1)

zmo
zmo

Reputation: 24812

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

Upvotes: 2

Related Questions