neilwatson has asked for the wisdom of the Perl Monks concerning the following question:

After fork && exit; how will I know the current PID? getppid; returns 1 as the parent has already exited.

Neil Watson
watson-wilson.ca

Replies are listed 'Best First'.
Re: PID after fork && exit
by edan (Curate) on May 12, 2003 at 16:12 UTC

    $$ will always give you the current process ID:

    print "PID before fork: $$\n"; fork && exit; print "PID after fork: $$\n";

    Output:

    PID before fork: 21314 PID after fork: 21315

    (Your mileage may vary)

    --
    3dan
Re: PID after fork && exit
by Fletch (Bishop) on May 12, 2003 at 16:07 UTC

    Read perldoc perlipc and perldoc perlvar harder.

    perl -le 'print "parent pid $$"; if( my $p = fork ) {print "parent got + child $p"; exit; } else { print "child pid $$"; exit }'
Re: PID after fork && exit
by smitz (Chaplain) on May 12, 2003 at 16:00 UTC
    fork returns the child PID, or 0 for the parent, AFAIK

    Smitz
      That's very confusing what you write.

      If fork fails, undef is returned. If fork succeeds, different values are returned in the parent and the child. In the child, fork returns 0, while in the parent, the process ID of child is returned. This is the only convenient time for the parent to get the process ID of the child. A parent can get the process ID of the child when it's reaping the child with some form of wait call, but then the child has already finished. Otherwise, the parents rests nothing else than walking the process list.

      Abigail

Re: PID after fork && exit
by neilwatson (Priest) on May 12, 2003 at 16:17 UTC