Open In App

sorting in fork()

Last Updated : 13 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite – Introduction of fork(), sorting algorithms Problem statement – Write a program to sort the numbers in parent process and print the unsorted numbers in child process. For example :

Input : 5, 2, 3, 1, 4

Output :
Parent process 
sorted numbers are
1, 2, 3, 4, 5


Child process 
numbers to sort are
 5, 2, 3, 1, 4

Explanation – Here, we had used fork() function to create two processes one child and one parent process.

  • fork() returns value greater than 0 for parent process so we can perform the sorting operation.
  • for child process fork() returns 0 so we can perform the printing operation.
  • Here we are using a simple sorting algorithm to sort the numbers in the desired order.
  • We are using the returned values of fork() to know which process is a child or which is a parent process.

Note – At some instance of time, it is not necessary that child process will execute first or parent process will be first allotted CPU, any process may get CPU assigned, at some quantum time. Moreover process id may differ during different executions. Code – 

CPP




// C++ program to demonstrate sorting in parent and
// printing result in child processes using fork()
#include <iostream>
#include <unistd.h>
#include <algorithm>
using namespace std;
 
// Driver code
int main()
{
    int a[] = { 1, 6, 3, 4, 9, 2, 7, 5, 8, 10 };
    int n = sizeof(a)/sizeof(a[0]);
    int id = fork();
 
    // Checking value of process id returned by fork
    if (id > 0) {
        cout << "Parent process \n";
 
        sort(a, a+n);
   
        // Displaying Array
        cout << " sorted numbers are ";
        for (int i = 0; i < n; i++)
            cout << "\t" << a[i];
 
        cout << "\n";
 
    }
 
    // If n is 0 i.e. we are in child process
    else {
        cout << "Child process \n";
        cout << "\n  numbers to be sorted are ";
        for (int i = 0; i < n; i++)
            cout << "\t" << a[i];      
    }
 
    return 0;
}


Output –

Output :
Parent process 
sorted numbers are 1 2 3 4 5 6 7 8 9 10

Child process 
numbers to be sorted are 1 6 3 4 9 2 7 5 8 10

Time Complexity: O(n log n)
Auxiliary Space: O(1)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads