The Wayback Machine - https://web.archive.org/web/20240918183714/https://www.geeksforgeeks.org/fork-system-call/
Open In App

fork() in C

Last Updated : 14 May, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The Fork system call is used for creating a new process in Linux, and Unix systems, which is called the child process, which runs concurrently with the process that makes the fork() call (parent process). After a new child process is created, both processes will execute the next instruction following the fork() system call.

The child process uses the same pc(program counter), same CPU registers, and same open files which use in the parent process. It takes no parameters and returns an integer value.

Below are different values returned by fork().

  • Negative Value: The creation of a child process was unsuccessful.
  • Zero: Returned to the newly created child process.
  • Positive value: Returned to parent or caller. The value contains the process ID of the newly created child process.

creating a fork process

Note: fork() is threading based function, to get the correct output run the program on a local system.

Please note that the above programs don’t compile in a Windows environment.

Example of fork() in C

C




#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
  
    // make two process which run same
    // program after this instruction
    pid_t p = fork();
    if(p<0){
      perror("fork fail");
      exit(1);
    }
    printf("Hello world!, process_id(pid) = %d \n",getpid());
    return 0;
}


Output

Hello world!, process_id(pid) = 31 
Hello world!, process_id(pid) = 32 

Example 2: Calculate the number of times hello is printed.

C




#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
    fork();
    fork();
    fork();
    printf("hello\n");
    return 0;
}


Output

hello
hello
hello
hello
hello
hello
hello
hello

Explanation

The number of times ‘hello’ is printed is equal to the number of processes created. Total Number of Processes = 2n, where n is the number of fork system calls. So here n = 3, 23 = 8 Let us put some label names for the three lines:

fork ();   // Line 1
fork ();   // Line 2
fork ();   // Line 3
       L1       // There will be 1 child process 
    /     \     // created by line 1.
  L2      L2    // There will be 2 child processes
 /  \    /  \   //  created by line 2
L3  L3  L3  L3  // There will be 4 child processes 
                // created by line 3

So there is a total of eight processes (new child processes and one original process). If we want to represent the relationship between the processes as a tree hierarchy it would be the following: The main process: P0 Processes created by the 1st fork: P1 Processes created by the 2nd fork: P2, P3 Processes created by the 3rd fork: P4, P5, P6, P7

             P0
         /   |   \
       P1    P4   P2
      /  \          \
    P3    P6         P5
   /
 P7

Example 3: Predict the Output of the following program.

C




#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
void forkexample()
{
    pid_t p;
    p = fork();
    if(p<0)
    {
      perror("fork fail");
      exit(1);
    }
    // child process because return value zero
    else if ( p == 0)
        printf("Hello from Child!\n");
  
    // parent process because return value non-zero.
    else
        printf("Hello from Parent!\n");
}
int main()
{
    forkexample();
    return 0;
}


Output

Hello from Parent!
Hello from Child!

Note: In the above code, a child process is created. 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.

Parent process and child process are running the same program, but it does not mean they are identical. OS allocates different data and states for these two processes, and the control flow of these processes can be different. See the next example:

Example 4: Predict the Output of the following program.

C




#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
  
void forkexample()
{
    int x = 1;
    pid_t p = fork();
      if(p<0){
      perror("fork fail");
      exit(1);
    }
    else if (p == 0)
        printf("Child has x = %d\n", ++x);
    else 
        printf("Parent has x = %d\n", --x);
}
int main()
{
    forkexample();
    return 0;
}


Output

Parent has x = 0
Child has x = 2

       or

Output

Child has x = 2
Parent has x = 0

Here, global variable change in one process does not affect two other processes because the data/state of the two processes is different. And also parent and child run simultaneously so two outputs are possible.

fork() vs exec()

The fork system call creates a new process. The new process created by fork() is a copy of the current process except for the returned value. On the other hand, the exec() system call replaces the current process with a new program.

Problems based on C fork()

1. A process executes the following code

C




for (i = 0; i < n; i++)
    fork();


The total number of child processes created is (GATE-CS-2008)

(A) n 
(B) 2^n – 1
(C) 2^n
(D) 2^(n+1) – 1

See this for a solution.

2. Consider the following code fragment: 

C




if (fork() == 0) {
    a = a + 5;
    printf("%d, %d\n", a, &a;);
}
else {
    a = a –5;
    printf("%d, %d\n", a, &a;);
}


Let u, v be the values printed by the parent process, and x, y be the values printed by the child process. Which one of the following is TRUE? (GATE-CS-2005)

(A) u = x + 10 and v = y
(B) u = x + 10 and v != y
(C) u + 10 = x and v = y
(D) u + 10 = x and v != y

See this for a solution.

3. Predict the output of the below program.

C




#include <stdio.h>
#include <unistd.h>
int main()
{
    fork();
    fork() && fork() || fork();
    fork();
  
    printf("forked\n");
    return 0;
}


See this for the solution

Related Articles :

This article is contributed by Team GeeksforGeeks and Kadam Patel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



Similar Reads

Creating child process using fork() in Python
Create a child process and display process id of both parent and child process. Fork system call use for creates a new process, which is called child process, which runs concurrently with process (which process called system call fork) and this process is called parent process. After a new child process created, both processes will execute the next
2 min read
fork() to execute processes from bottom to up using wait()
fork() system call is used to create a process generally known as child process and the process that created it is known as parent process. Now, all the processes that are created using fork() runs concurrently. But what if we want the last process created to execute first and in this manner bottom to up execution such that parent process executes
3 min read
Fork() - Practice questions
Prerequisite: basics of fork, fork and binary tree, Example1: What is the output of the following code? #include &lt;stdio.h&gt; #include &lt;unistd.h&gt; int main() { if (fork() || fork()) fork(); printf(&quot;1 &quot;); return 0; } Output: 1 1 1 1 1 Explanation: 1. It will create two process one parent P (has process ID of child process)and other
3 min read
fork() and Binary Tree
Given a program on fork() system call. #include &lt;stdio.h&gt; #include &lt;unistd.h&gt; int main() { fork(); fork() &amp;&amp; fork() || fork(); fork(); printf(&quot;forked\n&quot;); return 0; } How many processes will be spawned after executing the above program? A fork() system call spawn processes as leaves of growing binary tree. If we call f
4 min read
C Program to Demonstrate fork() and pipe()
fork() is used to create a child process. This child process is a copy of the original(parent) process. It is the primary method of process creation on Unix-like operating systems.( See this article for reference). Syntax: fork(); // It does not take any parameter, it returns // integer values. It may return negative, // positive or zero integer va
4 min read
Factorial calculation using fork() in C for Linux
Write a Unix C program using the fork() system call that generates the factorial and gives a sequence of series like 1, 2, 6, 24, 120... in the child process. The number of the sequence is provided in the command line. Examples: Input :gfg@ubuntu:~/$ gcc -o fork fork.c gfg@ubuntu:~/$ ./fork 6 Output :1 1 2 1 2 6 1 2 6 24 1 2 6 24 120 1 2 6 24 120 7
3 min read
Fork() Bomb
Prerequisite : fork() in CFork Bomb is a program that harms a system by making it run out of memory. It forks processes infinitely to fill memory. The fork bomb is a form of denial-of-service (DoS) attack against a Linux based system.Once a successful fork bomb has been activated in a system it may not be possible to resume normal operation without
3 min read
C vs BASH Fork bomb
Pre-requisites : Fork System Call Fork bomb Bash fork bomb : :(){:&amp;:&amp;};: Working in Unix : In Unix-like operating systems, fork bombs are generally written to use the fork system call. As forked processes are also copies of the first program, once they resume execution from the next address at the frame pointer, they also seek to create a c
3 min read
Difference between fork() and exec()
Every application(program) comes into execution through means of process, process is a running instance of a program. Processes are created through different system calls, most popular are fork() and exec() fork() pid_t pid = fork(); fork() creates a new process by duplicating the calling process, The new process, referred to as child, is an exact
4 min read
Calculation in parent and child process using fork()
Write a program to find sum of even numbers in parent process and sum of odd numbers in child process. Examples: Input : 1, 2, 3, 4, 5 Output : Parent process Sum of even no. is 6 Child process Sum of odd no. is 9 Explanation: Here, we had used fork() function to create two processes one child and one parent process. For child process fork() return
2 min read
Creating multiple process using fork()
Prerequisite - Introduction of fork, getpid() and getppid() Problem statement - Write a program to create one parent with three child using fork() function where each process find its Id. For example : Output :parent 28808 28809 my id is 28807 First child 0 28810 my id is 28808 Second child 28808 0 my id is 28809 third child 0 0 Explanation - Here,
3 min read
fork() and memory shared b/w processes created using it
Prerequisite: fork() in C So when we do a fork() what are the sections the two process actually share? Is the heap memory per process? Are the global variables shared? Will malloc return the same address to both? Let us run the program below and take a look at the output of it to clear the questions above. C/C++ Code // C program to demonstrate wor
4 min read
C Programming Language Tutorial
In this C Tutorial, you’ll learn all C programming basic to advanced concepts like variables, arrays, pointers, strings, loops, etc. This C Programming Tutorial is designed for both beginners as well as experienced professionals, who’re looking to learn and enhance their knowledge of the C programming language. What is C?C is a general-purpose, pro
8 min read
printf in C
In C language, printf() function is used to print formatted output to the standard output stdout (which is generally the console screen). The printf function is a part of the C standard library &lt;stdio.h&gt; and it can allow formatting the output in numerous ways. Syntax of printfprintf ( "formatted_string", arguments_list);Parametersformatted_st
5 min read
Pattern Programs in C
Printing patterns using C programs has always been an interesting problem domain. We can print different patterns like star patterns, pyramid patterns, Floyd's triangle, Pascal's triangle, etc. in C language. These problems generally require the knowledge of loops and if-else statements. In this article, we will discuss the following example progra
15+ min read
C Programs
To learn anything effectively, practicing and solving problems is essential. To help you master C programming, we have compiled over 100 C programming examples across various categories, including basic C programs, Fibonacci series, strings, arrays, base conversions, pattern printing, pointers, and more. These C Examples cover a range of questions,
8 min read
Switch Statement in C
Switch case statement evaluates a given expression and based on the evaluated value(matching a certain condition), it executes the statements associated with it. Basically, it is used to perform different actions based on different conditions(cases). Switch case statements follow a selection-control mechanism and allow a value to change control of
8 min read
C Programming Interview Questions (2024)
At Bell Labs, Dennis Ritchie developed the C programming language between 1971 and 1973. C is a mid-level structured-oriented programming and general-purpose programming. It is one of the old and most popular programming languages. There are many applications in which C programming language is used, including language compilers, operating systems,
15+ min read
scanf in C
In C programming language, scanf is a function that stands for Scan Formatted String. It is used to read data from stdin (standard input stream i.e. usually keyboard) and then writes the result into the given arguments. It accepts character, string, and numeric data from the user using standard input.scanf also uses format specifiers like printf.sc
2 min read
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Since C is a structured language, it has some fixed rules for programming. One of them includes changing the size of an array. An array is a collection of items stored at contiguous memory locations. As can be seen, the length (size) of the array above is 9. But what if there is a requirement to change this length (size)? For example, If there is a
9 min read
Format Specifiers in C
The format specifier in C is used to tell the compiler about the type of data to be printed or scanned in input and output operations. They always start with a % symbol and are used in the formatted string in functions like printf(), scanf, sprintf(), etc. The C language provides a number of format specifiers that are associated with the different
6 min read
Substring in C++
The substring function is used for handling string operations like strcat(), append(), etc. It generates a new string with its value initialized to a copy of a sub-string of this object. In C++, the header file which is required for std::substr(), string functions is &lt;string&gt;. The substring function takes two values pos and len as an argument
8 min read
Strings in C
A String in C programming is a sequence of characters terminated with a null character '\0'. The C String is stored as an array of characters. The difference between a character array and a C string is that the string in C is terminated with a unique character '\0'. C String Declaration SyntaxDeclaring a string in C is as simple as declaring a one-
8 min read
Decision Making in C (if , if..else, Nested if, if-else-if )
The conditional statements (also known as decision control structures) such as if, if else, switch, etc. are used for decision-making purposes in C programs. They are also known as Decision-Making Statements and are used to evaluate one or more conditions and make the decision whether to execute a set of statements or not. These decision-making sta
11 min read
Operators in C
In C language, operators are symbols that represent operations to be performed on one or more operands. They are the basic components of the C programming. In this article, we will learn about all the built-in operators in C with examples. What is a C Operator?An operator in C can be defined as the symbol that helps us to perform some specific math
14 min read
C Pointers
Pointers are one of the core components of the C programming language. A pointer can be used to store the memory address of other variables, functions, or even other pointers. The use of pointers allows low-level memory access, dynamic memory allocation, and many other functionality in C. In this article, we will discuss C pointers in detail, their
14 min read
Data Types in C
Each variable in C has an associated data type. It specifies the type of data that the variable can store like integer, character, floating, double, etc. Each data type requires different amounts of memory and has some specific operations which can be performed over it. The data type is a collection of data with values having fixed values, meaning
7 min read
C Arrays
Array in C is one of the most used data structures in C programming. It is a simple and fast way of storing multiple values under a single name. In this article, we will study the different aspects of array in C language such as array declaration, definition, initialization, types of arrays, array syntax, advantages and disadvantages, and many more
15+ min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The &amp; (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.  The | (bitwise OR) in C takes two n
7 min read
C Language Introduction
C is a procedural programming language initially developed by Dennis Ritchie in the year 1972 at Bell Laboratories of AT&amp;T Labs. It was mainly developed as a system programming language to write the UNIX operating system. The main features of the C language include: General Purpose and PortableLow-level Memory AccessFast SpeedClean SyntaxThese
6 min read