in reply to Getting PID of process forked by backticks

Why do you want the PID of a process that has already exited? Another process may have that PID now. The number is unique and only while the process is running!

Or are you under the impression that you can run Perl code in parallel with the backquotes?

-- Randal L. Schwartz, Perl hacker
Be sure to read my standard disclaimer if this is a reply.

  • Comment on Re: Getting PID of process forked by backticks

Replies are listed 'Best First'.
Re^2: Getting PID of process forked by backticks
by paulski (Beadle) on Jun 08, 2005 at 04:30 UTC

    What happens if the forked process blocks?

    From PERL's point of view, backticks block until the process returns. But from the OS point of view processes are running concurrently.

    If I know the PID (returned by open), I can kill the process after a certain amount of time has elasped by catching an ALRM signal. The signal will interrupt the control flow and the signal handler can kill the "timed out" process.

      If that's what you want, I'd recommend using fork. I did something similar a while back, using fork, as described in Timing and timing out Unix commands. If you get it working without using fork, I'd be interested in seeing your code.

        I had a similar requirement, and came up with this:

        my %p; sub killchildren { my $ppid = shift; chomp(my $out = `ps -o pid --no-headers --ppid $ppid`); for (split /\n/, $out) { killchildren($_); kill 9, $_; } } sub homicide { killchildren($$); $p{fg}{timeout} = 1; } sub fg { my ($cmd, $timeout) = @_; $p{fg}{timeout} = 0; my $out; eval { local $SIG{ALRM} = q(homicide); alarm $timeout; $out = `$cmd`; alarm 0; }; return $out unless $p{fg}{timeout}; return q(TIMEOUT); } # # TEST # my $out = fg("echo Hi; sleep 5", 1); print "Out = $out\n"; $out = fg("echo Bye; sleep 5", 10); print "Out = $out\n";

        The test example had the following output:

        ~/src$ ./a.pl
        Out = TIMEOUT
        Out = Bye