tags:

views:

35

answers:

2

I am trying to figure out children processes of a given parent from ps fwaux (there may very well be a better way to do this). Basically, I have daemons running that may or may not have a child process running at any given time. In another script I want to check if there are any child processes, and if so do something. If not, error out.

ps fwaux|grep will show me the tree, but I'm not exactly sure what to do with it. Any suggestions would be great.

+2  A: 

You could parse the results of a call to Proc::ProcessTable:

use Proc::ProcessTable;

my $processes = Proc::ProcessTable->new(enable_ttys => 0);
my @children = grep { $_->cmndline =~ /some_pattern_matching_your_children/ }  @{$processes->table};

# or:
my @children = grep { $_->ppid == $parent_pid } @{$processes->table};

But stepping back to the larger problem of tracking children: instead of grepping the process table, the children should track themselves using pid files. File::Pid can help you with that.

Ether
Unless I am misunderstanding something, Pid files wouldn't help me since I am checking for children from a completely separate script. I.e. script1 creates the child and would manage the pid file, how would script2 know what to do with the pid file?
Magic Hat
@Magic: The file(s) contain the pids of the children, so in your management script you just check to see if the pids correspond to processes that are still running, so you don't have to grep the process table.
Ether
Ah that makes sense. I guess the problem here is that the parent app is written in Java, so I won't have access to the pid. (yeah, I didn't develop this)
Magic Hat
A: 

As an update, this is what I ending up doing (in bash ...)

while :
do
        # find parent ids 
        PIDS="`ps -eao bsdtime,pid,command | egrep -v egrep | egrep 'processname' | awk '{print $2}'`"
        count=0
        # loop through ppids and look for children
        for j in ${PIDS}
        do
                #echo "Parent process = $j"
                CPID="`ps -ef | awk '$3 == J {print $2}' J=$j`"
                for i in ${CPID}
                do
                        #echo "Child process = $i"
                        let count++
                done
        done

Then if count > 0, there are child processes.

Magic Hat