Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kill process on the left side of a pipe

Tags:

bash

process

pipe

I have the following in bash:

foo | bar

I want foo to die when the script is terminated (using a TERM signal). Unfortunately, none of them dies. I tried this:

exec foo | bar

This achieved absolutely nothing. Then I tried this:

function run() {
    "$@" &
    pid=$!
    trap "kill $pid" EXIT
    wait
}

run foo | bar

Again, nothing. Now I have one more process, and none of them dies when I terminate the parent.

like image 661
petersohn Avatar asked Aug 27 '18 14:08

petersohn


People also ask

How do you kill a process by a partial name?

Killing a Process We can kill the dummy_process using its alias name. In fact, we do this by specifying the -f option, which allows us to match the given process name with the full process name. However, the pkill command is easy to mishandle as it will kill any process that matches the given process name.

How do you find a process and kill it?

Kill a Process by the kill command To terminate a process, execute the kill command followed by PID. To locate the PID of a process, use the top or ps aux command, as explained above. To kill a process having PID 5296, execute the command as follows: kill 5296.


1 Answers

By killing the whole process group instead of just bash (the parent), you can send the kill signal to all children as well. Syntax examples are:

kill -SIGTERM -$!
kill -- -$!

Example:

bash -c 'sleep 50 | sleep 40' & sleep 1; kill -SIGTERM -$!; wait; ps -ef | grep -c sleep
[1] 14683
[1]+  Terminated              bash -c 'sleep 50 | sleep 40'
1

Note that wait here waits for bash to be effectively killed which takes some milliseconds. Also note that the final result (1) is the 'grep sleep' itself. A result of 3 would show that this did not work as two additional sleep processes would still be running.

The kill manual mentions:

-n
where n is larger than 1. All processes in process group n are signaled.
When an argument of the form '-n' is given, and it is meant to denote a
process group, either the signal must be specified first, or the argument
must be preceded by a '--' option, otherwise it will be taken as the signal
to send.
like image 158
Camusensei Avatar answered Sep 28 '22 06:09

Camusensei