pidcheck.c 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /*
  2. * pidcheck - simple test of fork and getpid
  3. *
  4. * relies only on fork, console write, getpid and _exit
  5. *
  6. * child prints its pid, parent prints childs pid and its own
  7. *
  8. */
  9. #include <unistd.h>
  10. #include <string.h>
  11. #include <stdlib.h>
  12. #include <stdio.h>
  13. #include <err.h>
  14. /* declare this volatile to discourage the compiler from
  15. optimizing away the parent's delay loop */
  16. volatile int tot;
  17. int
  18. main(int argc, char *argv[])
  19. {
  20. (void)argc;
  21. (void)argv;
  22. pid_t pid,pid2;
  23. int i;
  24. pid = fork();
  25. if (pid < 0) {
  26. warn("fork");
  27. }
  28. else if (pid == 0) {
  29. /* child */
  30. pid2 = getpid();
  31. /* print the child's PID, as seen by the child */
  32. printf("C: %d\n",pid2);
  33. }
  34. else {
  35. /* parent */
  36. /* try to delay long enough for the child to finish printing */
  37. tot = 0;
  38. for(i=0;i<1000000;i++) {
  39. tot++;
  40. }
  41. /* print the child's PID, as seen by the parent */
  42. printf("PC: %d\n",pid);
  43. /* print the parent's PID */
  44. pid2 = getpid();
  45. printf("PP: %d\n",pid2);
  46. }
  47. return(0);
  48. }