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

Hi monks

Is there any Perl function to get a child pid of a process running, by just passing only the parent process pid

regards
seeker

Replies are listed 'Best First'.
Re: Function to get a child pid
by wazoox (Prior) on Oct 21, 2005 at 13:21 UTC

    If your process isn't a child of your script, no. I think it depends heavily on the operating system running, too.

    The easiest way I think of on Unix systems is something like this :

    use strict; use warnings; sub get_childpids { my $father=shift; # linux style my @exec=`ps -o pid --ppid $father` or die "can't run ps! $! \n"; # SYS V style : use shell, needs cleansing # my @exec=`ps -eo ppid | grep $father` or die "can't run ps! $! \ +n"; # BSD style : use shell, needs cleansing # my $exec=`ps aux | grep $father` or die "can't run ps! $! \n"; shift @exec; chomp @exec; return @exec; }
Re: Function to get a child pid
by blazar (Canon) on Oct 21, 2005 at 12:59 UTC
    It's not entirely clear to me what you want to do. When you fork the pid of the child is returned to parent. Now you want to call a function that returns the pid of a child process "already running". But a child of... what? Do you mean to call this function in the parent? Then you would have better saved it at fork time instead.

    Also you want to "get the child pid of a process running, by just passing only the parent process pid". But a parent can have many childs...

      fork is not accepting arguments. This will help me when I call this function recursively to find all the child pid.So can you explain me how to pass pid as argument to fork

        Maybe I wasn't clear, and I apologize for that... I wasn't suggesting fork as a function "to get a child pid of a process running, by just passing only the parent process pid". Because I can hardly make sense of such a request.

        Said this, maybe you just want to get a list of all the childs of a given (parent) process. If so, then you may use Proc::ProcessTable to search amongst all processes those that are childs of the given parent. You will be particularly interested in Proc::ProcessTable::Process's ppid() method.

        To put all this together is left as an exercise to the reader.

Re: Function to get a child pid
by gri6507 (Deacon) on Oct 21, 2005 at 13:57 UTC
    If the child process was started by the parent process in Perl, then you could find the child's pid simply by
    my $pid = fork(); if (!defined($pid)) { print "Could not fork!\n"; } elsif ($pid) { print " child pid was $pid\n"; } else { print "I am the child\n"; }