歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux下C的fork函數應用實例

Linux下C的fork函數應用實例

日期:2017/3/1 10:40:57   编辑:Linux編程

題目:寫出一段程序,創建4個子進程,每個子進程都打印“Hello”後立刻終止,父進程等待4個子進程都終止後,打印“Bye”,然後終止。

答:這裡有兩種結構的程序,各位看哪種順眼就看哪種吧~

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<sys/types.h>
  4. #include<sys/wait.h>
  5. int main()
  6. { char *msg = "Hello";
  7. pid_t pid;
  8. int count = 0;
  9. for(count = 0;count<4;count++)
  10. { pid = fork();
  11. if (0 != pid) //父進程執行
  12. wait(NULL);
  13. else //子進程執行
  14. { printf("Child %d: ", count);
  15. puts("Hello");
  16. exit(0);
  17. }
  18. }
  19. printf("Father : ");
  20. puts("Bye");
  21. exit(0);
  22. }
  23. /*
  24. fork1:
  25. pid = fork();
  26. if (0 != pid) //父進程執行
  27. { wait(NULL);
  28. if (count < 3)
  29. { count++;
  30. goto fork1;
  31. }
  32. else
  33. { printf("Father : ");
  34. puts("Bye");
  35. }
  36. }
  37. else //子進程執行
  38. { printf("Child %d: ", count);
  39. puts("Hello");
  40. }
  41. exit(0);
  42. }*/
Copyright © Linux教程網 All Rights Reserved