Reputation: 1038
I am firing up an ssh command that will fork itself out and will be running even after the script is done. So the code looks like this:
ssh_proc = Popen(['ssh', '-f', '-N', '-L', local_forward, local_user_host], stdin=PIPE, stdout=PIPE)
print ssh_proc.pid
stat = ssh_proc.poll()
As you can see ssh -f
forks ssh as a process and runs after the script is done - i need to get the pid of that ssh process. The print statement above, will only print out the pid of Popen process. Any suggestions?>
Upvotes: 2
Views: 7749
Reputation: 6049
If you use:
shell=True
as a parameter with your Popen command, your pid will match the running shell's pid instead of the command. As long as the process isn't a daemon and detaches itself from the terminal, you should be able to kill the process just by adding that in. (You would have to change the command to NOT be a list, but a string.
It's in the python docs: http://docs.python.org/2/library/subprocess.html#subprocess.Popen.pid
Upvotes: 0
Reputation: 992955
Although you have passed the -f
switch to ssh, your program is not in control (and not informed) about what activities the ssh program itself does. There is no direct way for your program to discover that ssh has forked and to find the second child pid.
There may be an indirect way to obtain this information, however. You could enumerate the active processes and look for one whose parent is the ssh_proc.pid
.
Upvotes: 1