Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

need help in understanding return values in fork().

Status
Not open for further replies.

whn

Programmer
Oct 14, 2007
265
US
I worte a piece of perl code like this:

Code:
print "This is the original process #: $$\n";
my $ret = &watchProcess;
[COLOR=red][b]print "\$\$ = $$, \$ret = $ret\n";[/b][/color]

exit 0;

sub watchProcess {
  my $pid1 = fork();
  my $msg;
  if (not defined $pid1) {
    print "First Resources not avilable.\n";
  }
  elsif ($pid1 == 0) {
    print "This is the parent Process, \$\$ = $$, \$pid1 = $pid1\n";
    sleep 1;
    my $pid2 = fork();
    if (not defined $pid2) {
      print "Second Resources not avilable.\n";
    }
    elsif ($pid2 == 0) {
      print "This is the parent Process again, \$\$ = $$, \$pid1 = $pid1, \$pid2 = $pid2\n";
      #sleep 1;
      return "P2";
    }
    else { # 2nd child process
      print "This is 2nd Child Process. \$\$ = $$, \$pid1 = $pid1, \$pid2 = $pid2\n";
      waitpid($pid2, 0);
    }
    [b]return "P1";[/b]
  }
  else { # 1st child process
    print "This is 1st Child Process. \$\$ = $$, \$pid1 = $pid1\n";
    waitpid($pid1, 0);
    [COLOR=blue][b]sleep 1;[/b][/color] 
  }
}

Test run 1:
Code:
% [b]./tt.pl[/b]
This is the original process #: 24502
This is the parent Process, $$ = 24503, $pid1 = 0
This is 1st Child Process. $$ = 24502, $pid1 = 24503
This is the parent Process again, $$ = 24504, $pid1 = 0, $pid2 = 0
$$ = 24504, $ret = P2
This is 2nd Child Process. $$ = 24503, $pid1 = 0, $pid2 = 24504
$$ = 24503, $ret = P1
$$ = 24502, $ret = 1

Test run 2 (this time the sleep call in blue is commented out):
Code:
This is the original process #: 24699
This is the parent Process, $$ = 24700, $pid1 = 0
This is 1st Child Process. $$ = 24699, $pid1 = 24700
This is the parent Process again, $$ = 24701, $pid1 = 0, $pid2 = 0
$$ = 24701, $ret = P2
This is 2nd Child Process. $$ = 24700, $pid1 = 0, $pid2 = 24701
$$ = 24700, $ret = P1
$$ = 24699, $ret = 24700

Can someone explain to me why the 2nd return value is a ps number?

Thanks.



 
not an answer.. but have you ever tried parallel::forkmanager? I used it once and have never looked back.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[noevil]
Travis - Those who say it cannot be done are usually interrupted by someone else doing it; Give the wrong symptoms, get the wrong solutions;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top