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.