Search code examples
cforkpid

C Program - How to get child's child pid in a parent [After fork]


Parent-> fork
------------1st Child(A)-> fork again
-------------------->1st Child's Child(Aa)

If I am the parent, how to get the child's child(Aa) pid in C program? Or how to get all the pid within this group?


Solution

  • There's not a direct way to get the child pid as for the parent pid (getppid()), but...

    fork() returns one of three values: child pid, 0, and -1.

    1. child pid is returned to the parent.
    2. 0 is returned to the child in the parent's code.
    3. -1 is returned when the fork() had error(s).

    ... so you already have the child(rens) pid(s) before and after they fork(). If you want the child pid after execl, for example, the easiest way is to just hang on to it when it is returned by fork(), i.e.; store it.

    If that's not efficient enough for you there's the possibility, as a commenter commented, you could set up a pipe() or two for communicating it back to the parent.

    int io[2];
    pipe(io);
    

    io[0] is in; io[1] is out. You would use write() and read().