fork() and script execution afterwards
- From: "Tom Storey" <tom@xxxxxxxxx>
- Date: Fri, 1 Jun 2007 00:08:53 +0930
Ive got a question about script execution after a fork() which I havnt been
able to find an answer to on google yet, but Im still looking (Ive fork'd my
searching :-P)
I have this simple test script:
==========================
#!/usr/local/bin/perl
use strict;
my ($pid, $x, @child, $ischild);
print "BEGIN\n\n";
for ($x = 1; $x <= 5; $x++) {
if (not defined($pid = fork())) {
die "couldnt fork: \"$!\"\n";
} elsif ($pid) {
push(@child, $pid);
} else {
print "This is child $x starting at " . localtime() . "\n";
sleep($x);
print "Child $x terminating at " . localtime() . "\n";
exit(0);
}
}
foreach(@child) {
waitpid($_, 0);
}
1;
==========================
Fiarly straight forward, and it works beautifully.
My question is, for each of the child processes that are spawned, I dont see
"BEGIN" outputted to the screen.
Is this because the "program counter" in each of the childs continues from
where it was in the parent too?
The reason I ask is because Ive been trying to devise a way of executing a
child process without actually beginning the whole script over again. This
is because in my real script I want to perform a database query to determine
just how many childs I need to fork to complete my process.
But now Im beginning to wonder whether I actually need to borhter trying to
avoid executing the top half of the script each time the child is spawned,
if the PC continues from where it was in the parent, the child will never
return to the beginning of the script. That would be so nice! :-)
If this is true, where I print BEGIN I could place my database code, and
replace the for loop with a while loop that runs through each database
record and forks a new child if neccessary.
Thanks,
Tom
.
- Follow-Ups:
- Re: fork() and script execution afterwards
- From: Andrew Fedyashov
- Re: fork() and script execution afterwards
- Prev by Date: Re: Multiple Line Pattern Match problem
- Next by Date: Re: Email::Folder->messages returns only one element
- Previous by thread: stumped by graphics display problem...
- Next by thread: Re: fork() and script execution afterwards
- Index(es):
Relevant Pages
|