×

C++ Fork

A new process known as a "child process" is created with the fork system function and runs concurrently with the process that invoked fork() (parent process). Both processes will carry out the next instruction following the fork() system call once a new child process has been started. The same CPU registers, program counter, and open files that the parent process utilises are used by the child process. In this article, we will discuss the fork in detail. Keep reading to know more about this thing.

What is the fork?

A new child process is created via fork(). When fork() is used in the parent program, it produces a child process that uses a distinct address space but shares an exact copy of the parent program's address space. The same memory region is shared by the parent and child processes, but their address spaces are distinct. It returns an integer value and requires no arguments. Various values returned by the fork are listed below ().

  1. Negative Value: The procedure of producing a child was unsuccessful.
  2. Zero: The child process that was just started was returned.
  3. Returned to the caller or parent with a positive value. The newly generated child process's process ID is contained in the value.

Example 1:

#include<iostream>
#include<unistd.h>
#include<sys/types.h>
using namespace std;
int main()
{
  fork();
  cout<<"World is beatiful"<<endl;
  
  return 0;
}

Output:

Fork in C++

Example 2:

#include <string>
#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "err.h"


using namespace std;
int main ()
{
 pid_t pid;
 int i;


 cout << "My process id = " << getpid() << endl;


 for (i = 1; i <= 4; i++)
  switch ( pid = fork() ) {
  case -1:
    printf("Error in fork");


  case 0:
    cout << "Child process: My process id = " << getpid() << endl;
    cout << "Child process: Value returned by fork() = " << pid << endl;
    return 0;


  default:
    cout << "Parent process. My process id = " << getpid() << endl;
    cout << "Parent process. Value returned by fork() = " << pid << endl;




 }  
 return 0;
 }

Output:

Fork in C++

The number of forks

This is a fascinating query. Because the parent process and the child process both share the same memory section, we already know this. This indicates that the same program is being run by both of these processes. However, inside the child process, the fork() function just returns 0. (zero). The fork() call is followed by the continuation of the execution. When one child process generates a new set of child processes, that's when things get interesting. The power of two is increased since there are now two processes when one parent process generates a second child process.

Example 1:

#include<iostream>
#include<unistd.h>
#include<sys/types.h>
int main()
{
  fork();
  fork();
  fork();
  cout<<"World is beautiful"<<endl;
  
  return 0;
}

Output:

Fork in C++

Code Explanation:

The number of processes created is equal to how many times the word "hello" is printed. Total Processes = 2n, where n is the number of system calls for forking. As a result, n = 3 and 2^3 equals 8. There are so eight steps in total (new child processes and one original process). The following would be a tree hierarchy representation of the relationship between the processes:

The key procedure: P0

Processes brought about by the first fork: P1

Processes produced by the second fork: P2, P3.

Third-fork processes include P4, P5, P6, and P7.

Example 2:

#include <iostream>
#include <sys/types.h>
#include <unistd.h>
void forkexample()
{
	if (fork()==0)
		printf("It is Child!\n");
	else
		printf("It is Parent!\n");
}
int main()
{
	forkexample();
	return 0;
}

Output:

Fork in C++

Code Explanation:

The code above creates a child process. Fork() produces a result of 0 for the parent process and a positive integer for the child process. Due to the parallel operation of the parent process and child process, in this case, two outputs are available. Therefore, we are unsure of which process will receive control from the OS first: the parent process or the child process. Although the same program is being performed by both the parent and child processes, they are not identical. These two processes receive different amounts of data and states from the OS. Therefore their control flows may differ.

Example 3:

#include <iostream>
#include <sys/types.h>
#include <unistd.h>


void forkexample()
{
	int x = 1;


	if (fork() == 0)
		printf("Child has x = %d\n", ++x);
	else
		printf("Parent has x = %d\n", --x);
}
int main()
{
	forkexample();
	return 0;
}

Output:

Fork in C++

Code Explanation:

Because the data and states of the two processes are separate, a global variable change in one process has no effect on the other two processes. Additionally, the parent and child operate concurrently, allowing for two outputs.


Related Topics

rand() and srand() in C / C++

In this tutorial, we'll explore the syntax, usage, and examples of the C++ STL functions rand() and srand(). What exactly is rand()? The C++ STL's built-in rand() function is defined in the...

3 minutes read.

C++ Maximum Index Problem

Given an array A[] of positive integers. We will find the maximum of (j-i) such that i and j are the indexes of A[] and A[i] <= A[j], i<=j For...

5 minutes read.

Reserved Keywords in C++

What are reserved keywords in C++? There are a few keywords that cannot be used as identifiers as those words are reserved for some other purposes, such keywords are called reserved...

15 minutes read.

C++ Constructor

Constructor is a specific method in C ++ that is automatically called when an object is created. Typically, it is used to set the data members of a new object....

4 minutes read.

C++ program to read string using cin.getline()

C++ program to read string using cin.getline() C++ getline() is a standard library feature for reading a string or a line from an input source. A getline() function gets characters from...

3 minutes read.

C++ Bidirectional Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.

Vector Size in C++

What are Vectors?  In the C++ programming language, vectors are run-time sequence containers representing arrays with variable sizes, which are contained within STL (Standard Template Library). They utilize contiguous storage spaces...

6 minutes read.

C++ Enumeration

C++ Enumeration In C++, Enum is a special data type that contains some fixed sets of components that have various applications in the programming. Enum works fine with fixed constant sets...

3 minutes read.

Constructor Overloading in C++

A Constructor is a class member function that is used to initialize the class's objects. Constructors have no return type and are called automatically when an object is formed. Constructor Characteristics Constructors...

3 minutes read.

Difference between Exit and Return

Define Exit() At the point when a client needs to leave a program from this capability is utilized. A void return type capability calls all capabilities enrolled at the exit and ends...

3 minutes read.

Private Inheritance in C++

Private inheritance is an inheritance in object-oriented programming (OOP) languages where a subclass derives from a superclass. Still, the derived class does not inherit the public and protected members of...

7 minutes read.

C++ Friend Functions

In C++, friends are special functions that are not a part of a class yet have access to its private and protected members. The friend keyword is used to declare...

4 minutes read.

C++ add two numbers using the function

Here we will learn how to add two numbers by creating function in C++. Let’s learn this with help of example. Code: - #include <iostream> using namespace std; int add_two_no(int a, int b); int main(){   int...

1 minute read.

Differences Between C Structures and C++ Structures

The below table clearly describes the differences between C and C++ programming languages Structures concepts where the core principle concepts like static members, data handling, pointers, access modifiers, the importance...

3 minutes read.

Template Specialization in C++

Template is a feature of C++. With the help of a template, we can write the code only once and use that code multiple times. For example, there is a...

4 minutes read.

Fast Input and Output in C++

In competitive programming, it's critical to read input as quickly as possible in order to save time. "Warning: Big I / O data, be aware of certain languages (but most...

3 minutes read.

C++ User Defined Exceptions

Overriding and inheriting exception class capabilities may be used to define the new exception. Exception handling can also be used with classes. We may also make an exception for user-defined...

4 minutes read.

While Loop Examples in C++

While Loop A while loop repeats all code in its body, also known as a while statement, as long as a specific condition is satisfied. The loop ends if or when...

4 minutes read.

Auto keyword in C++

The primary function of auto keyword is to assign and detect the value of the data type automatically in C++. The compiler knows the data type of the variable by...

2 minutes read.

This keyword in C++

This keyword in C++ is a pointer which points to the object. It is passed as an argument to functions which helps in accessing the object. It is used for a...

3 minutes read.