Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does fork() work?

Tags:

c

fork

Im really new to forking, what is the pid doing in this code? Can someone please explain what comes out at line X and line Y ?

#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#define SIZE 5
int nums[SIZE] = {0,1,2,3,4};
int main()
{
    int i;
    pid_t pid;
    pid = fork();
    if (pid == 0) {
        for (i = 0; i < SIZE; i++) {
            nums[i] *= -i;
            printf("CHILD: %d ",nums[i]); /* LINE X */
        }
    }
    else if (pid > 0) {
        wait(NULL);
        for (i = 0; i < SIZE; i++)
            printf("PARENT: %d ",nums[i]); /* LINE Y */
    }
    return 0;
}
like image 220
PhoonOne Avatar asked Feb 27 '13 00:02

PhoonOne


People also ask

What does fork () do in C?

fork() in C This fork system call is used to create a new process. This newly created process is known as child process. The current process which is creating another child process is called the parent process. A child process uses the same program counter, CPU register, same files that are used by the parent process.

What is fork () explain it with an example?

fork() returns 0 in the child process and positive integer in the parent process. Here, two outputs are possible because the parent process and child process are running concurrently. So we don't know whether the OS will first give control to the parent process or the child process.

What does fork () do in Linux?

fork() creates a new process by duplicating the calling process. The new process is referred to as the child process. The calling process is referred to as the parent process. The child process and the parent process run in separate memory spaces.

How does fork work under the hood?

Under the hood, each process's memory page has a bit flag that is the copy-on-write flag that indicates whether that page should be copied before being written to. fork(2) marks every writeable page in a process with that bit. Each page also maintains a reference count.


1 Answers

fork() duplicates the process, so after calling fork there are actually 2 instances of your program running.

How do you know which process is the original (parent) one, and which is the new (child) one?

In the parent process, the PID of the child process (which will be a positive integer) is returned from fork(). That's why the if (pid > 0) { /* PARENT */ } code works. In the child process, fork() just returns 0.

Thus, because of the if (pid > 0) check, the parent process and the child process will produce different output, which you can see here (as provided by @jxh in the comments).

like image 195
MatthewD Avatar answered Nov 14 '22 12:11

MatthewD