Just call fork() as many times as you need...
# Create 10 child processes
for (1..10){
my $pid = fork();
last unless defined $pid; # Too many processes already?
unless($pid){
# Child code here
exit;
}
}
# wait() for kids
while(($pid = wait()) > 0){
# Check $? here
}
--perlplexer | [reply] [d/l] |
Hi
Thank you very much for replying back.
When I fork in a loop, how do I ensure that all the child
processes are executing concurrently. My main aim to use
fork is to execute different subroutines in a cincurrent
fashion. Many thanks for your help.
| [reply] |
fork() creates a new process, so, as long as you have enough CPU power, all fork()ed processes may be executing concurrently. I say "may be" because it really depends on what they do, on their priority in the system, and on the number of CPUs that the OS has at its disposal.
--perlplexer
| [reply] |
Here's an example of one parent forking multiple children.
The Perl Cookbook has great examples about this topic.
You'd really want to make sure you're looping around the fork() and keeping track of the number of living children you have at the moment. Other than that and IPC, it's mostly just everyday programming.
Christopher E. Stith
use coffee;
| [reply] |
Hi
Thank you very much for replying back. I had a question
regarding multiple forks in a loop:
1. How do I ensure that all child processes are running conurrently
2. Also, How can I execute different subroutines for each child
Looking forward to hear from you.
Thanks
| [reply] |
1) That requires IPC of some sort.
2) TMTOWTDI.
2a) You could increment a status variable meant specifically for this purpose before the fork() in the parent, and each child would then get their private version of that variable after the fork() at the value that was current during the fork(). You could then run a different sub or exec() a different file based on the value of that variable.
2b) This is more complex than the above. You could have each child communicate back to the parent to ask.
2c) You could keep a file/database entry for each task that has been started (like a pid file) and start whichever one is next.
My vote for #2 is 2a.
Christopher E. Stith
use coffee;
| [reply] |