ristov has asked for the wisdom of the Perl Monks concerning the following question:
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. While waiting for the child can be easily done with waitpid(pid, 0), signals do not interrupt waitpid() with EINTR error code. To solve this problem, one could use the following code with non-blocking waitpit():
$term = 0; $SIG{TERM} = sub { $term = 1; }; for (;;) { $p = waitpid($pid, WNOHANG); # where did the child disappear? if ($p == -1) { exit(1); } # child has terminated if ($p == $pid && (WIFEXITED($?) || WIFSIGNALED($?))) { exit($?>>8); } # TERM has arrived, forward it to child and exit if ($term) { kill('TERM', $pid); exit(0); } # check the child again after 1 second sleep(1); }
However, I am interested whether the same task can be accomplished with blocking waitpid() which consumes less CPU time. There is one very interesting recipe which involves the use of eval:
http://blog.kazuhooku.com/2015/02/writing-signal-aware-waitpid-in-perl.htmlNevertheless, I am wondering whether it would be OK to use the blocking waitpid() with a different signal handler for the same purpose:
# waitpid($pid,WNOHANG) returns 0 if the child process # exists and has not terminated $SIG{TERM} = sub { waitpid($pid,WNOHANG) || kill('TERM', $pid); exit(0 +); } # waitpid loop for (;;) { $p = waitpid($pid, 0); # where did the child disappear? if ($p == -1) { exit(1); } # child has terminated if ($p == $pid && (WIFEXITED($?) || WIFSIGNALED($?))) { exit($?>>8); } }
In the signal handler, waitpid($pid, WNOHANG) is used for checking if the child process exists, in order to avoid sending TERM to a non-existing process. Since I am not too familiar with Perl internals, I am not sure if it is OK if the signal handler is invoked in the middle of blocking waitpid(), in order to call waitpid() again in non-blocking mode from the handler. Can anyone provide some insights? If this approach has flaws, I would go with previous code examples.
regards, risto
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: using waitpid() with signals
by kcott (Archbishop) on Jan 21, 2017 at 03:34 UTC | |
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 | |
|
Re: using waitpid() with signals
by Anonymous Monk on Jan 21, 2017 at 23:03 UTC |