fork download
  1. #include <stdio.h>
  2. #include <unistd.h> // for fork(), execlp(), getpid()
  3. #include <sys/types.h> // for pid_t
  4. #include <sys/wait.h> // for wait()
  5. #include <stdlib.h> // for exit()
  6.  
  7. #define MAX_COUNT 5
  8.  
  9. // Function declarations
  10. void parentProcess();
  11. void childProcess();
  12.  
  13. int main()
  14. {
  15. pid_t pid;
  16.  
  17. // Create child process
  18. pid = fork();
  19.  
  20. // If fork fails
  21. if (pid < 0)
  22. {
  23. printf("Fork failed\n");
  24. return 1;
  25. }
  26.  
  27. // Child process
  28. if (pid == 0)
  29. {
  30. childProcess();
  31. }
  32. // Parent process
  33. else
  34. {
  35. parentProcess();
  36. }
  37.  
  38. return 0;
  39. }
  40.  
  41. // Child Process Function
  42. void childProcess()
  43. {
  44. printf("Output of execlp system call:\n");
  45.  
  46. // Executes 'ls' command
  47. execlp("/bin/ls", "ls", NULL);
  48.  
  49. // This line runs only if execlp fails
  50. printf("execlp failed\n");
  51. }
  52.  
  53. // Parent Process Function
  54. void parentProcess()
  55. {
  56. int i;
  57. pid_t processID;
  58.  
  59. // Wait for child process to complete
  60. wait(NULL);
  61.  
  62. // Get parent process ID
  63. processID = getpid();
  64.  
  65. // Print lines from parent
  66. for (i = 1; i <= MAX_COUNT; i++)
  67. {
  68. printf("Line from parent process = %d\n", i);
  69. }
  70.  
  71. printf("Parent process is done\n");
  72. printf("Parent Process ID = %d\n", processID);
  73.  
  74. exit(0);
  75. }
Success #stdin #stdout 0s 5316KB
stdin
Standard input is empty
stdout
prog
Line from parent process = 1
Line from parent process = 2
Line from parent process = 3
Line from parent process = 4
Line from parent process = 5
Parent process is done
Parent Process ID = 3210922