fork download
  1. /* main program illustrating the UNIX fork() system call.
  2. Compile using cc -o main main.c
  3. */
  4. #include <stdio.h>
  5. #include <stdio.h>
  6. #include <sys/types.h>
  7. #include <unistd.h>
  8.  
  9. int main() {
  10. pid_t pid1 = 0, pid2 = 0, pid3 = 0, pid4 = 0, pid5 = 0, pid6 = 0;
  11.  
  12. pid1 = fork();
  13. printf("pid1 has been executed!");
  14. if (pid1 == 0) { // Child process
  15. pid2 = fork();
  16. printf("A");
  17. printf("pid2 has been executed!");
  18. printf("Process %d created, Parent: %d\n", getpid(), getppid());
  19. } else { // Parent process executes execvp
  20. char *args[] = {"/bin/ls", NULL};
  21. execvp(args[0], args);
  22. }
  23.  
  24. printf("Process %d created, Parent: %d\n", getpid(), getppid());
  25. printf("B");
  26. pid3 = fork();
  27. if (pid4 != 0) { // Parent process
  28. printf("C");
  29. printf("Process %d created, Parent: %d\n", getpid(), getppid());
  30. char *args[] = {"/bin/ls", NULL};
  31. execvp(args[0], args);
  32. } else { // Child process
  33. if (pid1 != 0) { // If this is not the first child
  34. pid5 = fork();
  35. printf("Process %d created, Parent: %d\n", getpid(), getppid());
  36. char *args[] = {"/bin/ls", NULL};
  37. execvp(args[0], args);
  38. printf("D");
  39. }
  40. }
  41.  
  42. if (pid2 > 0) { // Only for the original parent process
  43. pid6 = fork();
  44. printf("E");
  45. printf("Process %d created, Parent: %d\n", getpid(), getppid());
  46. } else { // pid2 == 0 case
  47. printf("F");
  48. printf("Process %d created, Parent: %d\n", getpid(), getppid());
  49. char *args[] = {"/bin/ls", NULL};
  50. execvp(args[0], args);
  51. }
  52.  
  53. printf("G");
  54.  
  55. printf("Process %d created, Parent: %d\n", getpid(), getppid());
  56.  
  57. return 0;
  58. }
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
prog
pid1 has been executed!Apid2 has been executed!Process 3502448 created, Parent: 1
Process 3502448 created, Parent: 1
BEProcess 3502448 created, Parent: 1
GProcess 3502448 created, Parent: 1
pid1 has been executed!Apid2 has been executed!Process 3502448 created, Parent: 1
Process 3502448 created, Parent: 1
BEProcess 3502451 created, Parent: 1
GProcess 3502451 created, Parent: 1