Use subprocess.Popen
and Popen.pid
, you can get the pid of the process you started.
Like this:
>>> s = subprocess.Popen(["/bin/sleep"," 100 &"])
>>> print s.pid
34934
In the other shell, run ps -ef|grep sleep
, you can see:
WKPlus@mac:~/workspace/test >ps -ef|grep sleep
501 34934 34904 0 10:53下午 ttys000 0:00.00 /bin/sleep 100 &
501 34938 238 0 10:54下午 ttys002 0:00.00 grep sleep
Yes, s.pid
is exactly the pid of the process you just started.
And, be careful not to add an shell=True
to the subprocess.Popen(["/bin/sleep"," 100 &"])
, or you will get the pid of a shell, which is the parent process of /bin/sleep
.
The official explanation for this:
Note that if you set the shell argument to True, this is the process ID of the spawned shell.
Once you got the pid
, you can kill the specified process by using os.kill(pid)
after that.