1

In a bash script I normally use trap to clean up spawned processes:

function cleanup()
{
    jobs -l
    jobs -p | xargs -r -I {} kill -TERM {}
    jobs -l
    echo "do something after kill all jobs."
}
trap cleanup EXIT

However this does not work for process groups:

function cleanup()
{
    jobs -l
    jobs -p | xargs -r -I {} kill -TERM {}
    jobs -l
    echo "do something after kill all jobs."
}
trap cleanup EXIT
(sleep 100 | tee /tmp/sleep_test.log) | tee sleep_test2.log &
ps -ax -o pid,pgid,ppid,args | grep sleep
jobs -l
sleep 1

the jobs -p give out a ppid of process group of (sleep 100 | tee ...) and a process of tee ... The process group cannot be killed as above. It need to do kill -TERM -PGID. Is there any easy way to let jobs output process group PGID? Or is there any command can kill process group via PPID and process PID with a uniform interface?

update: kill -TERM 0 does not work here since it kill itself also. But I still need to do something after kill all jobs.

Wang
  • 7,250
  • 4
  • 35
  • 66
  • What happened to [this question](https://stackoverflow.com/questions/59830142/how-to-kill-process-groups-in-trap)? Did you try to `kill 0` on linux? You can edit your questions if you want to provide some new info, etc. Doesn't [What's the best way to send a signal to all members of a process group?](https://stackoverflow.com/questions/392022/whats-the-best-way-to-send-a-signal-to-all-members-of-a-process-group) answer your question? – KamilCuk Jan 20 '20 at 21:16
  • 1
    @KamilCuk please check the update – Wang Jan 20 '20 at 21:37
  • Trap the signal if you don't want to kill yourself: `trap : TERM; kill -TERM 0`. –  Jan 21 '20 at 03:24

1 Answers1

0

The only way I found is killing sub-processes directly.

#!/usr/bin/env bash

function cleanup()
{
    jobs -l
    for p in $(jobs -p); do
        kill $(pgrep -P $p)
    done
    jobs -l
    echo "do something after kill all jobs."
}
trap cleanup EXIT
(sleep 100 | tee /tmp/sleep_test.log) | tee sleep_test2.log &
ps -ax -o pid,pgid,ppid,args | grep sleep
jobs -l
sleep 1

I tried to kill PGID, which didn't work for me.

Philippe
  • 20,025
  • 2
  • 23
  • 32