Kill the parent of a child pipe process

6,761

Enclose your command with parentheses:

( tail -f z | grep 'd' ) &
kill -- -$!

This will kill the whole sub-process.

Here, by specifying a negative PID to kill, we kill the whole process group. See man 1 kill:

Negative PID values may be used to choose whole process groups; see the PGID column in ps command output.

Or man 2 kill:

If pid is less than -1, then sig is sent to every process in the process group whose ID is -pid.

However, kill -PID will only work if job control is enabled in bash (the default for interactive shells). Else, your subprocess won't have a dedicated process group and the kill command will fail with kill: (-PID) - No such process

To work around that, either activate job control in bash (set -m), or use pkill -P $!

Share:
6,761

Related videos on Youtube

user1005909
Author by

user1005909

Updated on September 18, 2022

Comments

  • user1005909
    user1005909 over 1 year

    I have a small script to demonstrate what I want to do

    #!/bin/bash
    > z
    tail -f z | grep 'd' &
    echo $!
    

    The $! gives the PID of the grep process. I want to be able to kill the tail process at the same time as killing the grep process. Doing kill "pid of grep"does not kill the tail process. Nor does killall grep. I could use killall tail but I think this would be dangerous.

  • user1005909
    user1005909 over 7 years
    This doesn't seem to work. I executed this script and echoed the $!. Then I killed the process and appended "r", then "d". But the grep was still running and it echoed the "d" to stdout. Furthermore, killing that pid still shows the tail and grep in ps ux
  • xhienne
    xhienne over 7 years
    @user1005909 Sorry, I answered too quickly. Answer updated
  • user1005909
    user1005909 over 7 years
    Looks like there's an extra - on -$!. Anyway, this works only if the kill statement is in the bash script. Echoing the pid, then using kill -- pid from another shell doesn't work.
  • xhienne
    xhienne over 7 years
    @user1005909 The minus sign is intended, don't remove it! I have amended my answer with some documentation.
  • user1005909
    user1005909 over 7 years
    I see. I was getting -bash: kill: (-pid) - No such process. But this lead me to use pkill -P pid which works as I want.
  • xhienne
    xhienne over 7 years
    @user1005909 That's weird. I have never had any issue with the command kill -- -PID. I've just tried it again with Debian, Ubuntu and SLES, and it works fine.
  • user1005909
    user1005909 over 7 years
  • G-Man Says 'Reinstate Monica'
    G-Man Says 'Reinstate Monica' almost 6 years
    You tried what?  The other answer?  If you refer to another answer, please say so clearly.