![]() |
VOOZH | about |
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.
Table of Content
#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
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.