in reply to using waitpid() with signals
G'day ristov,
Welcome to the Monastery.
"I am trying to write the code which would wait for the child process to exit -- but if the code gets the TERM signal while waiting, the child process should be terminated with the same signal. ... I am interested whether the same task can be accomplished with blocking waitpid() ..."
This code demonstrates how you could do this:
#!/usr/bin/env perl -l use strict; use warnings; use constant SLEEP_TIME => 20; my $pid = fork; die "Can't fork()" unless defined $pid; if ($pid) { print "Parent: $$; Child: $pid"; local $SIG{TERM} = sub { print "Parent received signal: @_"; kill TERM => $pid if kill 0 => $pid; }; print "Waiting on child ..."; waitpid($pid, 0); print "Child terminated."; } else { print "Child: $$"; local $SIG{TERM} = sub { print "Child received signal: @_"; die "Child died via signal handler.\n"; }; sleep SLEEP_TIME; exit; }
Running without any intervention:
Parent: 28186; Child: 28187 Waiting on child ... Child: 28187 ... SLEEP_TIME seconds pass Child terminated.
Running and sending TERM to the parent:
Parent: 28192; Child: 28193 Waiting on child ... Child: 28193 ... on another command line: kill -TERM 28192 Parent received signal: TERM Child received signal: TERM Child died via signal handler. Child terminated.
Running and sending TERM to the child:
Parent: 28201; Child: 28202 Waiting on child ... Child: 28202 ... on another command line: kill -TERM 28202 Child received signal: TERM Child died via signal handler. Child terminated.
The signal handler in the child was purely for demonstration purposes. Here's the output, from similar runs, with it removed.
Parent: 28405; Child: 28406 Waiting on child ... Child: 28406 ... SLEEP_TIME seconds pass Child terminated.
Parent: 28419; Child: 28420 Waiting on child ... Child: 28420 ... kill -TERM 28419 Parent received signal: TERM Child terminated.
Parent: 28430; Child: 28431 Waiting on child ... Child: 28431 ... kill -TERM 28431 Child terminated.
"... checking if the child process exists, in order to avoid sending TERM to a non-existing process."
That's handled by "... if kill 0 => $pid;". See kill.
See also: perlipc: Signals.
— Ken
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: using waitpid() with signals
by ristov (Initiate) on Jan 21, 2017 at 08:40 UTC | |
by kcott (Archbishop) on Jan 21, 2017 at 21:40 UTC | |
by ristov (Initiate) on Jan 21, 2017 at 22:51 UTC |