How to kill both process and subprocess?

I asked a question to know how to get multiple lines of message from Python’s subprocess module.

The problem is that in the course of testing, I had to kill the python process that runs gnuchess process. Using ^c in the command line seems to kill the python process, but not the gnuprocess.

For killing gnuchess, I get the pid with ps aux | grep gnuchess and run kill -9 PID. Are there other methods to kill both python and gnuchess process?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

There is a standard method, if the programs cooperate. Run kill -- -42 where 42 is the pid of the parent process. This sends a signal to all the processes in the process group lead by process 42 (the minus sign before the pid means process group).

Normally, if you run your python script from a shell prompt and it simply forks gnuchess, the two processes should remain in the same process group. But this doesn’t seem to be the case, since Ctrl+C sends SIGINT to the whole foreground process group.

Gnuchess might be in its own process group because it made itself a session leader (but I don’t know why it would do this), or because you’ve double-forked it (python forks a shell which forks gnuchess). A double fork is probably avoidable, but I can’t tell you how without seeing your code.


A reasonably reliable and POSIX-compliant way of finding the pid of the gnuchess process is

gnuchess_pids=$(ps -A -o pid= -o cmd= | awk '$2 ~ /(^|/)gnuchess$/ {print $1}')

Specific unix variants may have better ways of achieving this, such as pgrep.

Method 2

Try:

pkill <processname>


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x