Search code examples
forkpid

Why different pids from fork() and getpid()?


My homework asks this:

Using the program below, identify the values of pid at lines A, B, C, and D. (Assume that the actual pids of the parent and child are 10 and 20, respectively.) Explain for each line the reason for the pid value.

#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
int main() {
    pid_t pid, pid1;
    /* fork a child process */
    pid = fork();
    if (pid < 0) { /* error occurred */
        fprintf(stderr, "Fork Failed\n");
        return 1;
    }
    else if (pid == 0) { /* child process */
        pid1 = getpid();
        printf("child: pid = %d\n",pid); /* A */
        printf("child: pid1 = %d\n",pid1); /* B */
    }
    else { /* parent process */
        pid1 = getpid();
        printf("parent: pid = %d\n",pid); /* C */
        printf("parent: pid1 = %d\n",pid1); /* D */
        wait(NULL);
    }
    return 0;
}

When I run it I get (for example):

parent: pid = 1586
parent: pid1 = 1585
child: pid = 0
child: pid1 = 1586

Why does fork() and getpid() return different pids for what's supposedly the same process?


Solution

  • You should first understand the return values of both function:

    • fork returns 0 in the child process and a non-zero value in the parent process; this non-zero value is the child process' PID.
    • getpid returns the PID of the current process; current means whoever is calling the getpid function.

    First, in your code, even though the line pid1 = getpid() is the same, the caller is different. In the else if block it was the child process, and in the else block it was the parent. Therefore the two pid1s are different in the output.

    Second, in the parent process, pid (fork's return value) is the child process' PID, not itself's. The reason fork returns child process' PID is to allow the parent process to communicate with and control the child.