What does fork() do, and what does it return?
MediumConceptProcesses & Threads
Answer
fork() is the Unix/Linux system call that creates a new process, the child, as a copy of the calling process, the parent. Both continue from the instruction after fork(), and the return value tells them apart: 0 in the child, the child's PID in the parent, and -1 (negative) in the parent if no child could be created.
- Copy-on-write (COW): parent and child initially share the same physical pages, marked read-only, and a page is copied only when one of them writes to it. This makes
fork()fast. - Each then has its own copy of every variable, so a change in one is not seen by the other.
- A shell runs a command by calling
fork(); the child callsexec()to load the program while the parent callswait(). - Calling
fork()n times in a row, unconditionally, gives 2^n processes in total.
Example:
int x = 10;
pid_t pid = fork();
if (pid == 0) { x++; printf("child: x = %d\n", x); }
else { printf("parent: x = %d\n", x); }
Output (order may vary): parent: x = 10 and child: x = 11. Similarly, fork(); fork(); printf("hi\n"); prints hi four times.
More in Processes & Threads
| # | Problem | Platform | Difficulty | Open | 1st1st Visit | 2nd2nd Visit | RevRevise |
|---|---|---|---|---|---|---|---|
| 1 | What is the difference between a process and a thread? | Concept | Easy | Read the answer to What is the difference between a process and a thread? | |||
| 2 | What are the states of a process, and what is a PCB? | Concept | Easy | Read the answer to What are the states of a process, and what is a PCB? | |||
| 3 | What is a context switch, and why is it considered overhead? | Concept | Medium | Read the answer to What is a context switch, and why is it considered overhead? | |||
| 4 | What does fork() do, and what does it return? | Concept | Medium | Read the answer to What does fork() do, and what does it return? | |||
| 5 | What are zombie and orphan processes? | Concept | Medium | Read the answer to What are zombie and orphan processes? |