Example of fork() system call

  • 3

    What's the output of the following code snippet?

    // From Advanced Programming in the Unix Environment Figure 8.1
    int glob = 6; 
        int var; 
        pid_t pid; 
        var = 88;
        printf("before fork\n"); 
        if ((pid = fork()) < 0) {
            err_sys("fork error");
        } else if (pid == 0) {
        } else {
        printf("pid = %d, glob = %d, var = %d\n", getpid(), glob, var);

    before fork
    pid = 430, glob = 7, var = 89
    pid = 429, glob = 6, var = 88

    First met this problem from the interview with VMWare.
    The fork() system call is called once and returns twice. The process which calls fork() system call is the parent process, the new process which is created by fork() is called the child process. The only difference in the returns is that it returns 0 in child process but returns the child process PID in the parent process. The child process will get a copy of the parent process's context. In child process, when we modify the local and global variables which are located in stack and heap respectively of the child process, only the child process will be affected with output:
    pid = 430, glob = 7, var = 89
    While parent process will print the original value before the fork:
    pid = 429, glob = 6, var = 88

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.