Solved [Solved] script that can kill all children

graudeejs

Son of Beastie

Reaction score: 694
Messages: 4,615

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.
 

SirDice

Administrator
Staff member
Administrator
Moderator

Reaction score: 7,542
Messages: 30,245

Re: script that can kill all children

Does the variable $pids contain the correct PIDs of the children?
 

Carpetsmoker

Daemon

Reaction score: 184
Messages: 1,012

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! ;)
 
OP
OP
graudeejs

graudeejs

Son of Beastie

Reaction score: 694
Messages: 4,615

Re: script that can kill all children

$pids are fine.

I can kill all children with
Code:
kill $pids
 

Toast

Member

Reaction score: 6
Messages: 51

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. :)
 
OP
OP
graudeejs

graudeejs

Son of Beastie

Reaction score: 694
Messages: 4,615

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)
 
Top