1 |
Hi, |
2 |
|
3 |
On Tue, 2 May 2006 17:42:26 +0100 (WEST) |
4 |
Jorge Almeida <jalmeida@××××××××××××.pt> wrote: |
5 |
|
6 |
> On Tue, 2 May 2006, Zac Slade wrote: |
7 |
> |
8 |
> > You can find the PID of the last backgrouned process using the bash variable |
9 |
> > $! |
10 |
> > |
11 |
> The child is not backgrounded! |
12 |
> > So something like: |
13 |
> > subprocess & |
14 |
> > $pid=$! |
15 |
> > |
16 |
> > Using trap along with maybe setting alarms should get you what you want. |
17 |
> > |
18 |
> Based on the suggestions of Uwe and Vladimir, I tried |
19 |
> trap 'pkill -TERM -P $$; kill -s TERM $$' TERM |
20 |
> <do something> |
21 |
> . /path/to/child.sh |
22 |
> <do something else> |
23 |
> Doesn't work, yet. Note that child.sh is a shell script that may execute |
24 |
> some other command (like rsync), so the "." by itself may not be enough. |
25 |
|
26 |
This can't work because of this (man bash): |
27 |
--snip |
28 |
If bash is waiting for a command to complete and receives a signal for |
29 |
which a trap has been set, the trap will not be executed until the |
30 |
command completes. |
31 |
--snip |
32 |
|
33 |
What instead works (just tested): |
34 |
--snip |
35 |
#!/bin/sh |
36 |
COMMAND="sleep 120" |
37 |
|
38 |
# First we background: |
39 |
$COMMAND & |
40 |
# Save the PID |
41 |
CHILDPID=$! |
42 |
# Trap the signal: |
43 |
trap "kill -TERM $CHILDPID" TERM |
44 |
# And wait for the Child to finish: |
45 |
wait $CHILDPID |
46 |
# reset signal handling: |
47 |
trap - TERM |
48 |
--snip |
49 |
|
50 |
Note that the code could hit a racing condition and should therefore |
51 |
not carelessly run by root on a machine with untrusted users. This is: |
52 |
The process may have finished before setting the signal handler. |
53 |
Other processes *might* reuse the PID afterwards and might get |
54 |
sig-TERM-ed until resetting the signal handler again. Probably a minor, |
55 |
depending on the script's usage. |
56 |
|
57 |
|
58 |
-hwh |
59 |
-- |
60 |
gentoo-user@g.o mailing list |