Saturday, September 4, 2010

Perl - Parent and child process

Creating a child process in Perl can be done with the fork command, Sample of the command :
defined ($pid = fork) or die "Cannot create thread";

By using the $pid value we can determine if we currently in the parent process or the child process, If its 0, We are currently in the child process, else, its the parent.

A Quick sample to demonstrate it:
my $pid;
print "
Parent PID is : $$ \n";

defined ($pid = fork) or die "Cannot create process";
if ($pid == 0)
{
print "
Child process Starting with pid : $$ \n";
}
else
{
print "
Parent process Continue with pid : $$ \n";
}
print "
Current PID is $$ (pid=$pid) \n";

The output of the previous script will be (I colored the Parent and the Child outputs):

Parent PID is : 2644

Parent process Continue with pid : 2644

Current PID is 2644 (pid=2645)

Child process Starting with pid : 2645

Current PID is 2645 (pid=0)

Note : $$ is the predefined name for the current running process.

No comments: