[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
How do terminate all child processes of a process?
From: |
Marshall, Simon |
Subject: |
How do terminate all child processes of a process? |
Date: |
Tue, 25 Nov 2003 11:22:56 -0000 |
Hi, I've a feeling this is a dumb question, but here goes and I hope
someone can help...
I have a script (call it A) that sets off background processes and
dutifully waits for them. Each background process is another script
(call it B) that sets off a foreground process (a binary executable in
this case, call it C). I want to be able to ^C (or whatever) script A
and cause scripts B and binaries C to terminate.
Here's how I naively think it should be done: A sets a trap and kills
Bs' pids. Unfortunately, it doesn't work. Bs gets killed. However, Cs
are not killed. Here's a simplified test case to illustrate it:
#!/bin/bash
# Script A
cmd="B 60"
exec $cmd & # Use exec to avoid an intermediate shell.
pid=$!
trap "echo $pid; kill $pid; exit 1" HUP INT QUIT TERM
wait $pid
status=$?
#!/bin/bash
# Script B
cmd="sleep $1"
eval $cmd
Here's it in action:
With A running: ps -fu marshals
UID PID PPID C STIME TTY TIME CMD
marshals 9954 9953 0 09:39 pts/2 00:00:00 -bash
marshals 10033 9954 0 09:41 pts/2 00:00:21 emacs
marshals 11415 9954 0 11:12 pts/2 00:00:00 /bin/bash ./A
marshals 11416 11415 0 11:12 pts/2 00:00:00 /bin/bash
/home/marshals/perth/c
marshals 11417 11416 0 11:12 pts/2 00:00:00 sleep 60
Now interrupt A, which outputs 11416 from the trap: ps -fu marshals
UID PID PPID C STIME TTY TIME CMD
marshals 9954 9953 0 09:39 pts/2 00:00:00 -bash
marshals 10033 9954 0 09:41 pts/2 00:00:21 emacs
marshals 11417 1 0 11:12 pts/2 00:00:00 sleep 60
See how 11416 (the shell running script B) has indeed been killed.
Unfortunately, it has not killed B's child process, the sleep process.
How can I arrange for all processes started by A or A's children, etc.,
to be killed when A is interrupted? Note that I also want to get the
exit status of B.
Many thanks in advance, Simon.
[Prev in Thread] |
Current Thread |
[Next in Thread] |
- How do terminate all child processes of a process?,
Marshall, Simon <=