Hi,
I am breaking my head to understand the below line of code in perl:
next if $pid = fork; # Parent goes to next server.
die "fork failed: $!" unless defined $pid;
Can anyone please explain me in detail as I am a slow learner?
Thanks,
Ali.
If fork
succeeds, it returns the process ID of the child process in the variable $pid
(of the parent process).
So, the parent will have some (non-zero) value in $pid
and the child process will have a 0 value in $pid
. And the next statements will be attempted to be executed by both the parent and the child processes.
If fork
fails, $pid
will be undef
.
So, the first statement says "if forking succeeds, go to the next loop block iteration (applicable for the parent process only as only the parent has a non-zero value in $pid
)".
So, the next statement ( die "fork failed: $!" unless defined $pid;
) is executed only by:
1) the parent process, if forking failed in the first statement, or
2) the child process, if forking is successful.
In 1), the parent process will die since $pid
will be undef.
In 2), the child process will not die (that is, it will continue with the next set of statements) as for the child, $pid
will be 0 (which is a defined value).
Elixir i have question too ... by wat u explained ..suppose if i want to run a date command on ten remote nodes i should place my command here ?
#!/usr/bin/perl
use strict;
use warnings;
print "Starting main program\n";
my @childs;
for ( my $count = 1; $count <= 10; $count++) {
my $pid = fork();
if ($pid) {
# parent
#print "pid is $pid, parent $$\n";
push(@childs, $pid);
} elsif ($pid == 0)
{
*/ Does the remote command go here /*
exit 0;
}
else {
die "couldnt fork: $!\n";
}
}
foreach (@childs) {
my $tmp = waitpid($_, 0);
print "done with pid $tmp\n";
}
print "End of main program\n";