fork download
  1. #include <iostream> // For input and output
  2. #include <unistd.h> // For fork(), getpid(), getppid(), wait()
  3. #include <sys/types.h> // For pid_t
  4. #include <sys/wait.h> // For wait()
  5.  
  6. using namespace std;
  7.  
  8. int main() {
  9. pid_t pid; // Variable to store process ID
  10.  
  11. // Print the PID of the main/original process
  12. cout << "Original Process Started. PID: " << getpid() << endl;
  13.  
  14. // Process Creation using fork()
  15. pid = fork(); // Creates a new child process
  16.  
  17. // Check if fork() failed
  18. if (pid < 0) {
  19. cerr << "Failed to create child process." << endl;
  20. return 1; // Exit with error
  21. }
  22.  
  23. // If fork() returns 0, it means this is the child process
  24. else if (pid == 0) {
  25. cout << "This is the Child Process." << endl;
  26. cout << "Child PID: " << getpid() << ", Parent PID: " << getppid() << endl;
  27.  
  28. // Child-specific tasks
  29. for (int i = 1; i <= 5; i++) {
  30. cout << "Child Process: Count " << i << endl;
  31. sleep(1); // Simulate some work with a sleep
  32. }
  33. }
  34.  
  35. // If fork() returns a positive value, this is the parent process
  36. else {
  37. cout << "This is the Parent Process." << endl;
  38. cout << "Parent PID: " << getpid() << ", Child PID: " << pid << endl;
  39.  
  40. // Parent-specific tasks
  41. for (int i = 1; i <= 3; i++) {
  42. cout << "Parent Process: Count " << i << endl;
  43. sleep(2); // Simulate some work with a sleep
  44. }
  45.  
  46. // Wait for the child process to complete
  47. wait(NULL); // Wait for the child process to finish
  48. cout << "Child process has completed." << endl;
  49. }
  50.  
  51. return 0; // End of program
  52. }
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
Original Process Started. PID: 2849479
This is the Parent Process.
Parent PID: 2849479, Child PID: 2849482
Parent Process: Count 1
This is the Child Process.
Child PID: 2849482, Parent PID: 2849479
Child Process: Count 1
Child Process: Count 2
Parent Process: Count 2
Child Process: Count 3
Child Process: Count 4
Parent Process: Count 3
Child Process: Count 5
Child process has completed.