×

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

Free vs delete() in C++

Free vs delete() in C++ In this section, we will learn about the free() function and also create a C ++ program of the delete operator. What is free() Function in C++? In...

4 minutes read.

Structure of C++ Program

Many people believe that C++, an object-oriented programming (OOP) language, is the finest language for developing demanding applications. A superset of the C language is C++. Java, a closely comparable...

4 minutes read.

Convex hull Algorithm in C++

The intersection of all convex sets containing a certain subset of a Euclidean space, or alternatively, the set of all convex combinations of points in the subset, defines the convex...

4 minutes read.

std::min in C++

std::min in C++ std::min is specified in the program code, used to calculate the lowest amount that has been transferred. When there's more of someone who returns first of them. It's used...

2 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.

Difference between "int main( ) and int main(void)" in C/C++

int main( ) function In the C/C++ programming language, int main() indicates a function that returns an integer at the end of the program execution. In general, a value of '0' indicates...

3 minutes read.

Returning Multiple Values from a Function using Tuple and Pair in C++

We may come across many situations where after the driver code's execution is performed in a code block, the return should be either multiple values or a single value possibly...

4 minutes read.

std::distance() in C++

The primary function of std::distance is to facilitate the total number of elements if we have two iterators. It is defined inside the header files. It has both magnitude and...

2 minutes read.

Nullptr in C++

What is Nullptr in C++? A null pointer value is represented by the term nullptr. Use a null pointer value to indicate that a native pointer type, inner pointer, or object...

3 minutes read.

Structure Sorting (By Multiple Rules) in C++

To understand the concept of Structure Sorting (By Multiple Rules) in C++, it is recommended to know the Structures concept in the C++ programming language. Here the scenario is pretty...

3 minutes read.

Palindrome using Do-while loop in C++

What is Palindrome? A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++...

5 minutes read.

Const Keyword in C++

The const programming language keyword will be covered in this section. The constant value that cannot change during program execution is defined using the const keywords. It implies that once...

9 minutes read.

Copy constructor

Let's start by learning what a constructor is before diving into the copy constructor in C++. What is a constructor? A constructor is a particular type of class member function that configures the objects of...

7 minutes read.

SET Data Structure in C++

Generally, in our home, we store food items in a fridge or kitchen efficiently to find them easily and use them. Similarly, in programming, we need to store the data...

6 minutes read.

How to declare a 2D array dynamically in C++

In this article, we will learn how to declare the dynamic array in C++. We also learn the initialization of a 2D array using a pointer in C++. Here, we...

3 minutes read.

Program to convert infix to postfix expression in C++

Parentheses are frequently employed in mathematical formulas to make their interpretation easier to understand. However, with computers, parenthesis in an expression might lengthen the time it takes to find a...

7 minutes read.

Templates in C++ vs Generics in Java

As the title suggests, there is no rivalry or there is no cut comparison between generics and templates in Java and C++, respectively. The main aim of this article is...

4 minutes read.

C++ Virtual Function

A virtual function is such function which is declared inside the base class and redefined by the derive class. C++ uses a virtual keyword to make a function as a virtual function. The virtual...

1 minute read.

Default arguments in C++

Arguments in a function are defined as the values supplied when the function is called. The source is the values supplied, and the destination is the receiving function. Let us...

3 minutes read.

C++ Queue

C++ queue: Queue in C++ is also a container adapter with the functionality of a queue. Queue is just the opposite of the stack in C++ because stack works on...

4 minutes read.