Solved [Solved] script that can kill all children

Kill all child processes.

Can anyone enlighten me what is wrong whit this script
master.sh
Code:
#!/bin/sh

echo "master:"
echo $$

./slave.sh 'a' &
./slave.sh 'bb' &

pids=`pgrep -P $$`
echo "pids:"
echo $pids

trap "kill -s 9 $pids" 0 1 2 9 15

wait

slave.sh
Code:
#!/bin/sh

i=0

while [ $i -lt 30 ]; do
  echo $1
  i=$(($i+1))
  sleep 1
done

The idea was that master launches few child processes (2 in this example) and when it receives any of kill signals, to kill child processes as well.
It doesn't work, and I don't understand why.
 
Re: script that can kill all children

Does the variable $pids contain the correct PIDs of the children?
 
Re: script that can kill all children

You may be able to use $!. From sh(1):

Code:
   $!      Expands to the process ID of the most recent background command
             executed from the current shell.  For a pipeline, the process ID is
             that of the last command in the pipeline.  If this parameter is
             referenced, the shell will remember the process ID and its exit
             status until the wait built-in command reports completion of the
             process.

Also: make a few more threads with titles like this, and expect a visit from the police! ;)
 
Re: script that can kill all children

$pids are fine.

I can kill all children with
Code:
kill $pids
 
Re: script that can kill all children

kill doesn't seem to like signal numbers when using "-s". (works fine in csh/tcsh)
Code:
kill: unknown signal 9; valid signals:
HUP INT QUIT ILL TRAP ABRT EMT FPE KILL BUS SEGV SYS PIPE ALRM TERM URG
STOP TSTP CONT CHLD TTIN TTOU IO XCPU XFSZ VTALRM PROF WINCH INFO USR1 USR2
Double quotes add a newline between each pid and kill doesn't like that.
echo "$pids"
trap "kill -KILL $pids" 0 1 2 9 15
Code:
46338
46337
master.sh: 46478: not found
kill: 46479: No such process
master.sh: 46478: not found
trap 'kill -KILL $pids' 0 1 2 9 15. :)
 
Re: script that can kill all children

Thanks Toast.

You solved this puzzle.

Code:
trap "pgrep -P $$ | xargs -n 1 kill -s KILL" 0 1 2 9 15

(or something like that did the trick)
 
Back
Top