#include <iostream> // For input and output
#include <unistd.h> // For fork(), getpid(), getppid(), wait()
#include <cstdlib> // For exit()
#include <sys/types.h> // For pid_t
#include <sys/wait.h> // For wait()
using namespace std;
int main() {
pid_t pid; // Variable to store process ID
cout << "Main Process Started. PID: " << getpid() << endl;
// Creating a Child Process
pid = fork(); // fork() creates a new child process
if (pid < 0) {
cerr << "Failed to create child process." << endl;
return 1; // Exit if fork fails
}
// Child Process Block
else if (pid == 0) {
cout << "Child Process Running..." << endl;
cout << "Child PID: " << getpid() << ", Parent PID: " << getppid() << endl;
// Do some task (simulation)
cout << "Child Process Doing Some Work..." << endl;
sleep(2); // Simulate work with a sleep
// Process Deletion
cout << "Child Process Completed. Deleting Itself Now..." << endl;
exit(0); // Child process terminates (gets deleted)
}
// Parent Process Block
else {
cout << "Parent Process Continues. PID: " << getpid() << endl;
cout << "Child Process was created with PID: " << pid << endl;
// Wait for the child process to finish
wait(NULL); // Parent waits for the child to terminate
cout << "Child Process has terminated. Parent Process Finished." << endl;
}
return 0; // End of program
}