fork0.c 764 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <sys/types.h>
  4. #include <sys/wait.h>
  5. int main(int argc, char **argv)
  6. {
  7. int counter = 0;
  8. int status;
  9. printf("parent: pid = %d; ppid = %d\n", getpid(), getppid());
  10. pid_t pid = fork();
  11. if (pid == 0)
  12. {
  13. // child process
  14. printf("child: pid = %d; ppid = %d\n", getpid(), getppid());
  15. int i = 0;
  16. for (; i < 5; ++i)
  17. {
  18. printf("child: counter=%d\n", ++counter);
  19. }
  20. }
  21. else if (pid > 0)
  22. {
  23. // parent process
  24. int j = 0;
  25. for (; j < 5; ++j)
  26. {
  27. printf("parent: counter=%d\n", ++counter);
  28. }
  29. wait(&status);
  30. if(status != 0){
  31. printf("parent: child exited with status %d\n", status);
  32. return 2;
  33. }
  34. }
  35. else
  36. {
  37. // fork failed
  38. printf("parent: fork() failed!\n");
  39. return 1;
  40. }
  41. return 0;
  42. }