Open In App

Create Processes with Fork in C++

fork() is a system call that creates a child process from the parent process. Whenever we call fork() from the parent program, a child process is created that has the exact copy of the address space. The important thing to remember is it shares the copy of the address space, not the copy itself. 

Syntax:



#include<unistd.h>
pid_t fork(void);

Significance

The following example demonstrates a multiprocessing environment. fork() call has no/null arguments and returns in both processes. In the parent process, the return id (pid) is that of a child process. if that fails, -1 is returned in the parent 



Example:




// C++ Program to demonstrate 
// a multiprocessing environment.
#include <iostream>
#include <unistd.h>
using namespace std;
  
int main()
{
    pid_t c_pid = fork();
  
    if (c_pid == -1) {
        perror("fork");
        exit(EXIT_FAILURE);
    }
    else if (c_pid > 0) {
        //  wait(nullptr);
        cout << "printed from parent process " << getpid()
             << endl;
    }
    else {
        cout << "printed from child process " << getpid()
             << endl;
    }
  
    return 0;
}

Output
printed from parent process 33
printed from child process 34

Create Multiple Processes using a fork

When a parent forks a child, there are two processes, parent and child. But when a child creates another child, the number increases in the power of 2. For example, when there are two forks( ) calls, n=2 and the total number of processes is 2^2 =4. 

Example: 




// C++ Program to Creating
// Multiple processes
// Using a fork
#include <iostream>
#include <unistd.h>
using namespace std;
  
int main()
{
    fork();
    fork();
    cout << "GeeksforGeeks" << endl;
  
    return 0;
}

Output
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks

The number of times our output statement is executed is the number of times the child process is created. Here in our example, n =3, so total process = 2^3 = 8. So there will be 8 lines in the output. Here total child process = 2^n – 1 = 8-1 = 7 (since one of them will be a parent process).




// C++ Program to
// Create Multiple processes
// Using a fork
#include <iostream>
#include <unistd.h>
using namespace std;
  
int main()
{
    fork();
    fork();
    fork();
    cout << "GeeksforGeeks" << endl;
  
    return 0;
}

Output
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks

Article Tags :