fork download
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <sys/wait.h>
  4.  
  5.  
  6. int main(void)
  7. {
  8. int ret;
  9.  
  10. for(int count=0; count < 2; count++) {
  11. ret = fork();
  12. switch(ret) {
  13. case -1:
  14. printf("fork error on pid %d run %d\n", (int)getpid(), count);
  15. break;
  16. case 0:
  17. printf("child pid %d run %d says hi!\n", (int)getpid(), count);
  18. break;
  19. default:
  20. printf("parent %d created child %d on run %d\n", (int)getpid(), ret, count);
  21. break;
  22. }
  23. while(wait(0) > 0);
  24. }
  25. return 0;
  26. }
  27.  
Success #stdin #stdout 0.01s 2680KB
stdin
Standard input is empty
stdout
child pid 7735 run 0 says hi!
child pid 7736 run 1 says hi!
child pid 7735 run 0 says hi!
parent 7735 created child 7736 on run 1
parent 7731 created child 7735 on run 0
child pid 7737 run 1 says hi!
parent 7731 created child 7735 on run 0
parent 7731 created child 7737 on run 1