Question-er XDD
Question-er XDD

Reputation: 767

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?

Upvotes: 1

Views: 11666

Answers (2)

grant sun
grant sun

Reputation: 120

here is a small example using pipe to correspond with sons:

#include <stdio.h>                
#include <signal.h>
#include <unistd.h>

int main(int argc, char  *argv[])
{
    pid_t ppid,pid,spid;    
    int io[2];
    pipe(io);
    if((pid=fork())>0){//father
        close(io[1]);
        read(io[0],&spid,sizeof(pid_t));
        ppid    = getpid();
        printf("father:%ld\tme:%ld\tson:%ld\n",ppid,pid,spid);
    }if(pid==0){//me
        close(io[0]);
        pid = getpid();
        ppid
            = getppid();
        if((spid=fork())>0){//me

        }else if(spid==0){//son
            spid    = getpid();
            write(io[1],&spid,sizeof(spid));
        }
    }

    return 0;
}

Upvotes: 1

ChiefTwoPencils
ChiefTwoPencils

Reputation: 13930

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().

Upvotes: 2

Related Questions