Im trying to get this fork thing down. I created a program that kills a child process after a certain amount of time if it hasn't exited. However I do not know how to get the child's PID, fork return 0 when its a child not its PID. Right now Im using 1 + the programs id but if something gets invoded before my fork I know that that might not be the case. So any idea's on how to get this. Thanks.
#!/usr/bin/perl -w
use strict;
use POSIX qw(:errno_h);
use POSIX qw(:sys_wait_h);
$SIG{CHLD} = "IGNORE";
my ($child, $script, $cleanup, $time);
&create_child;
sleep($time);
&reaper;
sub create_child {
unless($child = fork()) {
die "Cannot fork: $!" unless defined $child;
exec($script);
}
$child++;
}
# Some values are from get_args sub not shown
sub reaper {
if(kill 0 => $child) {
print "Child timed out, sending signal 15\n";
kill 15, $child;
exec($cleanup);
} elsif ($! == EPERM) {
print "Child has changed its UID\n";
} elsif ($! == ESRCH) {
print "Child is already dead\n";
} else {
warn "Could not check child's PID: $!\n";
}
}
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.