fork download
  1. #include <iostream> // For input and output
  2. #include <unistd.h> // For fork(), getpid(), getppid(), wait()
  3. #include <cstdlib> // For exit()
  4. #include <sys/types.h> // For pid_t
  5. #include <sys/wait.h> // For wait()
  6.  
  7. using namespace std;
  8.  
  9. int main() {
  10. pid_t pid; // Variable to store process ID
  11.  
  12. cout << "Main Process Started. PID: " << getpid() << endl;
  13.  
  14. // Creating a Child Process
  15. pid = fork(); // fork() creates a new child process
  16.  
  17. if (pid < 0) {
  18. cerr << "Failed to create child process." << endl;
  19. return 1; // Exit if fork fails
  20. }
  21.  
  22. // Child Process Block
  23. else if (pid == 0) {
  24. cout << "Child Process Running..." << endl;
  25. cout << "Child PID: " << getpid() << ", Parent PID: " << getppid() << endl;
  26.  
  27. // Do some task (simulation)
  28. cout << "Child Process Doing Some Work..." << endl;
  29. sleep(2); // Simulate work with a sleep
  30.  
  31. // Process Deletion
  32. cout << "Child Process Completed. Deleting Itself Now..." << endl;
  33. exit(0); // Child process terminates (gets deleted)
  34. }
  35.  
  36. // Parent Process Block
  37. else {
  38. cout << "Parent Process Continues. PID: " << getpid() << endl;
  39. cout << "Child Process was created with PID: " << pid << endl;
  40.  
  41. // Wait for the child process to finish
  42. wait(NULL); // Parent waits for the child to terminate
  43. cout << "Child Process has terminated. Parent Process Finished." << endl;
  44. }
  45.  
  46. return 0; // End of program
  47. }
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
Main Process Started. PID: 2874655
Parent Process Continues. PID: 2874655
Child Process was created with PID: 2874658
Child Process Running...
Child PID: 2874658, Parent PID: 2874655
Child Process Doing Some Work...
Child Process Completed. Deleting Itself Now...
Child Process has terminated. Parent Process Finished.