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

Hello. I would like to know if its possible to start a process with Perl, either using open, or some other means, backticks maybe, whatever. But once the parent process is running monitor it to see and retrieve the PID of any child processes that the original process may spawn or create.
Example Pseudo Code:
$parent = open PROC, "someProg|"; while(<PROC>){ if(childIsBorn){ push(@children, "PIDofChildProc"); } }
Is something like this possible?

Replies are listed 'Best First'.
Re: Working With Processes and Their children
by graff (Chancellor) on Jun 09, 2005 at 03:34 UTC
    Are you talking about a situation like:
    A spawns B B spawns C and D C spawns E D spawns F ang G ...
    and you want A to know all the sub-processes (B-G) that have descended from it? If so, the proper solution is likely to depend on what OS you're using. In *n*x, you can try looking at Proc::ProcessTable to see if that gives you what you want -- like being able to check processes by their parent-PID (ppid). Apart from that (so far as I know), you'd have to explicitly craft the sub-processes so that they report themselves somehow back to the primary parent (e.g. via pid files or whatever).

    But then, if the sub-processes you're spawning are not things that you are crafting yourself, then you're probably stuck with setting up the parent so that it monitors the process table to seek out all its descendants.

Re: Working With Processes and Their children
by thcsoft (Monk) on Jun 08, 2005 at 23:21 UTC
    perldoc perlopentut perldoc -f fork
    language is a virus from outer space.
Re: Working With Processes and Their children
by salva (Canon) on Jun 09, 2005 at 09:54 UTC
    in theory, Sys::Ptrace is what you are looking for, but it doesn't seem easy to use and only works on Linux x86.

    An alternative aproach is to run the command with strace and examine its output for new processes being forked.

Re: Working With Processes and Their children
by zentara (Cardinal) on Jun 09, 2005 at 11:33 UTC
    Here is a simple example using Proc::ProcessTable
    #!/usr/bin/perl use warnings; use strict; use Proc::ProcessTable; $SIG{CHLD} = 'IGNORE'; for(1..5){ sleep(10) and exit if(fork == 0); } for my $p (@{new Proc::ProcessTable->table}){ print $p->pid," child of $$\n" if($p->ppid == $$); }

    I'm not really a human, but I play one on earth. flash japh