1

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?

Craig H
  • 7,949
  • 16
  • 49
  • 61

3 Answers3

3
#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.
  • 27,409
  • 9
  • 73
  • 93
  • I believe this will get me the pid of my parent, not of my children – Craig H Jun 23 '09 at 21:42
  • 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. Jun 23 '09 at 21:45
2

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.

Community
  • 1
  • 1
Duck
  • 26,924
  • 5
  • 64
  • 92
1

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
  • 62,604
  • 14
  • 116
  • 151
  • 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. Jun 23 '09 at 21:47
  • I would agree, but it is a third party library that I have no authority or ability to change. – Craig H Jun 23 '09 at 21:52
  • 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 Jun 23 '09 at 22:28