简体   繁体   中英

Getting the pid of my children using linux system calls in C++

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?

#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;
}

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM