Open In App

Using fork() to produce 1 parent and its 3 child processes

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Creating processes and managing their execution sequence is a fundamental aspect of operating systems and concurrent programming. In this article, we’ll explore how to create a program that spawns four processes: one parent and three children, where each child terminates in a specific sequence. In this article, we’ll provide code implementations in C, C++, Python, Java, and JavaScript.

What is the use of fork() function?

  • The fork() call is a system call used to call the operating system to create a new process. Basically, there will be an exact copy of the calling process that will be created. The created exact copy of the process is called the child process.
  • Both the parent and the child processes have their own memory space, but they initially share the same memory contents.
  • Thus, after the fork() call, two identical processes are created. Execution of the parent process continues from the line following the call to fork(), and similarly, that of the child process continues from the same line.
  • The fork() function should return some different value for the parent and the child process: the parent returning the Process ID (PID) of the child process, and the child returning 0.
  • We can check the return value of fork() and thereby know if the program is running in the parent or child process.
  • This means changes in the memory space by one process do not affect another process. This more or less means that the child process can make changes to its variables or data without influencing the parent process, and vice versa.
  • This means that if in the parent process, a file is opened before a call to fork is executed, then it remains open after the fork call in both the parent and child processes because the child process inherits open file descriptors from the parent process.
  • The child process is a proceeding execution independent from the parent process, possible execution of different kinds of tasks or different code paths.
  • One of the functions that has universal recognition as being in Unix-like operating systems is fork(). It is the basic system call: the process of providing more abstracted facilities to create processes in many higher-level languages and libraries.

What are parent and child processes?

Parent Process:

  • The parent process is the original process that initiates the creation of another process, called the child process.
  • It typically continues to execute its code independently of the child process.
  • Most frequently, the parent process is the one that undertakes the likes of resource management coordination of communication between the processes, and control of the general program flow.
  • After a parent process has created a child process, it either waits for it to complete or continues its execution asynchronously.

Child Process:

  • The child process is created by the parent process using mechanisms like fork() or spawn().
  • It is a copy of the parent process at the time of its creation, sharing the same memory space and initial state.

Code Implementation

C++
#include <iostream>
#include <unistd.h>
#include <sys/wait.h>

int main() {
    pid_t pid;
    int i;

    // Loop to create 3 child processes
    for (i = 0; i < 3; i++) {
        pid = fork(); // Create a new process (fork)

        if (pid == 0) {
            // Child process
            std::cout << "Child " << i+1 << " PID: " << getpid() << std::endl; // Print child process ID
            sleep(1); // Simulate some work
            exit(0); // Terminate child process
        } else if (pid < 0) {
            // Error handling if fork fails
            perror("fork failed"); // Handle fork failure
            exit(1);
        }
    }

    // Parent process
    for (i = 0; i < 3; i++) {
        // Wait for each child process to terminate
        wait(NULL); // Wait for child processes to terminate
    }
    // Print parent process ID
    std::cout << "Parent PID: " << getpid() << std::endl; // Print parent process ID

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int main() {
    pid_t pid;
    int i;

    // Loop to create 3 child processes
    for (i = 0; i < 3; i++) {
        pid = fork(); // Create a new process (fork)

        if (pid == 0) {
            // Child process
            printf("Child %d PID: %d\n", i+1, getpid()); // Print child process ID
            sleep(1); // Simulate some work
            exit(0); // Terminate child process
        } else if (pid < 0) {
            // Error handling if fork fails
            perror("fork failed"); // Handle fork failure
            exit(1);
        }
    }

    // Parent process
    for (i = 0; i < 3; i++) {
        // Wait for each child process to terminate
        wait(NULL); // Wait for child processes to terminate
    }
    // Print parent process ID
    printf("Parent PID: %d\n", getpid()); // Print parent process ID

    return 0;
}
Java
import java.util.ArrayList;
import java.util.List;

class ProcessDemo {
    public static void main(String[] args) {
        List<Process> childProcesses = new ArrayList<>();
        long parentPID = ProcessHandle.current().pid();
        System.out.println("Parent PID: " + parentPID); // Print parent process ID

        // Loop to create 3 child processes
        for (int i = 0; i < 3; i++) {
            try {
                // Create a new process using ProcessBuilder
                ProcessBuilder pb = new ProcessBuilder("java", "ChildProcess", String.valueOf(i + 1));
                Process p = pb.start(); // Start a new process
                childProcesses.add(p); // Add the process to the list
                System.out.println("Child " + (i + 1) + " PID: " + p.pid()); // Print child process ID
            } catch (Exception e) {
                e.printStackTrace(); // Handle exceptions
            }
        }

        // Wait for each child process to terminate
        for (Process p : childProcesses) {
            try {
                p.waitFor(); // Wait for the process to terminate
            } catch (Exception e) {
                e.printStackTrace(); // Handle exceptions
            }
        }
    }
}
Javascript
const { fork } = require('child_process');

// Loop to create 3 child processes
for (let i = 0; i < 3; i++) {
    const child = fork('child.js', [i+1]); // Fork a new process
    child.on('exit', () => {
        // Print child process ID when child process exits
        console.log(`Child ${i+1} PID: ${child.pid}`); // Print child process ID
    });
}

// Print parent process ID
console.log(`Parent PID: ${process.pid}`); // Print parent process ID
Python3
import os
import time


def main():
    # Loop to create 3 child processes
    for i in range(3):
        pid = os.fork()  # Create a new process (fork)

        if pid == 0:
            # Child process
            print(f"Child {i+1} PID: {os.getpid()}")  # Print child process ID
            time.sleep(1)  # Simulate some work
            exit(0)  # Terminate child process
        elif pid < 0:
            # Error handling if fork fails
            print("Fork failed")  # Handle fork failure
            exit(1)

    # Parent process
    for i in range(3):
        # Wait for each child process to terminate
        os.wait()  # Wait for child processes to terminate

    # Print parent process ID
    print(f"Parent PID: {os.getpid()}")  # Print parent process ID


if __name__ == "__main__":
    main()

Output:

Child 1 PID: 1234
Child 2 PID: 1235
Child 3 PID: 1236
Parent PID: 1233

Conclusion

In this article, we’ve explored how to create a program that spawns four processes (one parent and three children) and manages their termination sequence in various programming languages including C, C++, Python, Java, and JavaScript. Understanding process creation and management is essential for building robust and scalable concurrent systems.



Last Updated : 13 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads