Search code examples
cprocessforkpid

getting child process ID from the parent using C


I'm trying to write a C program where I have one parent that create two childs.

My task is to retrieve the process ID of the parent of and both childs. For this I've been using getpid().

Now I've been asked to get the child information from the parent. I don't get how I can do this. Like how can I obtain the processing ID for a child from the parent?

I have this at the moment (simplified)

fork1 = fork();

if (fork1 < 0)
    fork error
else if (fork1 == 0) {
    child 1
    use getpid()
    use getppid()
} else {
    fork2 = fork();

    if (fork2 < 0)
        fork error
    else if (fork2 == 0) {
        child 2
        use getpid()
        use getppid()
    } else 
        parent again
}

Solution

  • After a minute of googling I found this page, where everything you need is written:

    System call fork() is used to create processes. It takes no arguments and returns a process ID.

    I highlighted the part which is importand for you, so you don't need to do anything to get the process IDs of the children. You have them already in fork1 and fork2!

    Here is some code which will print the PIDs from parent and children.

    #include <stdio.h>
    
    int main() {
      int fork1 = fork();
      if (fork1 < 0) {
        printf("error\n");
      } else if (fork1 == 0) {
        printf("I'm child 1\n");
        printf("child 1: parent: %i\n", getppid());
        printf("child 1: my pid: %i\n", getpid());
      } else {
        int fork2 = fork();
        if (fork2 < 0) {
          printf("error\n");
        } else if (fork2 == 0) {
          printf("I'm child 2\n");
          printf("child 2: parent: %i\n", getppid());
          printf("child 2: my pid: %i\n", getpid());
        } else {
          printf("I'm the parent\n");
          printf("The PIDs are:\n");
          printf("parent: %i\n", getpid());
          printf("child 1: %i\n", fork1);
          printf("child 2: %i\n", fork2);
        }
      }
      return 0;
    }