Phil for Humanity Phil for Humanity
A Guide for the Survival of Humankind and Helping the World, Society, and Yourself.



How to Fork a Child Process and Wait in Perl


Here is a very simple example of how to fork a child process and then wait for the child process to complete in Perl.

 # Fork child process
 my  $pid = fork();
  
 # Check if parent/child process
 if ($pid)
 { # Parent
   print "Started child process id: $pid\n";
 }
 elsif ($pid == 0)
 { # Child
   sleep 4; # Example child process
   exit 0;  # It is STRONGLY recommended to exit your child process
            # instead of continuing to run the parent script.
 }
 else
 { # Unable to fork
   die "ERROR: Could not fork new process: $!\n\n";
 }
 
 ###############################
 
 print "Waiting for the child process to complete...\n";
 waitpid ($pid, 0);
 print "The child process has finished executing.\n\n";
 

Give it a try.

by Phil for Humanity
on 20110425

Related Articles
 » Selective UNIX Wait
 » How to Implement "grep v" in Perl
 » Waiting for Child Process in Perl