Search code examples
cunixforkpid

why does the parent pid return a different value than getpid()?


According to the man page

getpid() returns the process ID (PID) of the calling process.

  1. In the following code why does the parent pid return a different value than getpid() ?
  2. Isn't the main process the same as the parent process?
  3. And why do I get different outputs when run on a different system?

#include <sys/types.h>                  
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int main(int argc, char const *argv[])
{

    printf("getpid = %d \n", (int)getpid());

    pid_t pid = fork();
    printf("fork returned %d \n", (int)pid);

    switch (pid)
    {
    case -1:
        perror("fork failed");
        break;

    case 0:
        printf("I am a child  with pid = %d\n", (int)pid);
        break;

    default:
        printf("I am a parent with pid = %d\n", (int)pid);

        break;

    }
    return 0;
}

output when i run :

getpid = 8208 
fork returned 8209 
I am a parent with pid = 8209
fork returned 0 
I am a child  with pid = 0

output when run on a different pc:

getpid = 2522 
fork returned 2523 
I am a parent with pid = 2522
fork returned 0 
I am a child  with pid = 2523

Solution

  • Yes, the parent process and main process are the same thing.

    This snippet of your code should give you a clue about the solution:

    switch (pid) {
        /* ... */
        case 0:
            printf("I am a child  with pid = %d\n", (int)pid);
            break;
    

    This effectively says "if pid is zero then the child pid is always zero". This obviously cannot be true, so it is your interpretation of fork()'s return value that is incorrect.

    The man page states:

    Upon successful completion, fork() returns a value of 0 to the child process and returns the process ID of the child process to the parent process.

    So the variable pid in the parent process is the pid of the child, NOT the parent's own pid.

    In the child process, you would need to call getpid() after fork() to get the child's own pid.