tags:

views:

281

answers:

3

I have a process that interfaces with a library that launches another process. Occasionally this process gets stuck and my program blocks in a call to the library. I would like to detect when this has happened (which I am doing currently), and send a kill signal to all these hung processes that are a child of me.

I know the commands to kill the processes, but I am having trouble getting the pids of my children. Does anyone know of a way to do this?

+2  A: 
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    FILE *fp = popen("ps -C *YOUR PROGRAM NAME HERE* --format '%P %p'" , "r");
    if (fp == NULL)
    {
        printf("ERROR!\n");
    }

    char parentID[256];
    char processID[256];
    while (fscanf(fp, "%s %s", parentID, processID) != EOF)
    {
         printf("PID: %s  Parent: %s\n", processID, parentID);

         // Check the parentID to see if it that of your process
    }

    pclose(fp);

    return 1;
}
RC
I believe this will get me the pid of my parent, not of my children
Craig H
It gets all process pids and their parents pids. If the parent pid is the one of your process, then it is a child of yours. You may also look at this similar question with stricter conditions:http://stackoverflow.com/questions/1009552/how-to-find-all-child-processes/1009598#1009598
RC
+1  A: 

I don't think "ps" is the answer. You could iterate the process list yourself to look for your own process's children, but it's a much better idea to modify the library so it provides the PIDs when you launch them.

This library must be pretty lame. What kind of deal do you have with its vendor? Can you not get on to their support to fix it?

MarkR
I agree. If you are able to modify the library in order to have the child pid returned, this is a much better solution.
RC
I would agree, but it is a third party library that I have no authority or ability to change.
Craig H
You might however, want to raise a ticket with the third party's support anyway, because you'll need a channel which works when a more serious problem arises.
MarkR
+2  A: 

This question is very similar to one asked the other day. I would suggest taking a look here to see if the answers are satisfactory in your case. Basically you will probably have to read through /proc.

Duck