fork download
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <stdlib.h>
  4. #include <sys/wait.h>
  5. main()
  6. {
  7. int pid ;
  8. printf("I'am the original process with PID %d and PPID %d.\n", getpid(), getppid()) ;
  9. pid = fork ( ) ; /* Duplicate. Child and parent continue from here */
  10. if ( pid != 0 ) /* pid is non-zero,so I must be the parent*/ {
  11. printf("I'am the parent with PID %d and PPID %d.\n", getpid(), getppid()) ;
  12. printf("My child's PID is %d\n", pid ) ;
  13. } else /* pid is zero, so I must be the child */ {
  14. printf("\nI'm the child with PID %d and PPID %d before sleeping.\n", getpid(), getppid()) ;
  15. sleep(4); /* make sure that the parent terminates first */
  16. printf("\nI'm the child with PID %d and PPID %d after waking up.\n", getpid(), getppid()) ;
  17. }
  18. printf ("PID %d terminates.\n", getpid()) ;
  19. return 0;
  20. }
Success #stdin #stdout 0s 3096KB
stdin
Standard input is empty
stdout
I'am the original process with PID 27117 and PPID 27115.
I'am the parent with PID 27117 and PPID 27115.
My child's PID is 27121
PID 27117 terminates.