经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C » 查看文章
c/c++ linux 进程 fork wait函数
来源:cnblogs  作者:小石王  时间:2018/10/18 9:03:33  对本文有异议

linux 进程 fork wait函数

fork:创建子进程

wait:父进程等待子进程结束,并销毁子进程,如果父进程不调用wait函数,子进程就会一直留在linux内核中,变成了僵尸进程。

fork函数的详细说明:fork

wait函数详细说明参考:wait

例子1:不注释掉exit(0)的话,子进程不会执行到printf("end pid: %d\n", getpid());这行。

  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <stdlib.h>
  4. #include <wait.h>//wait function
  5. int main(){
  6. pid_t pid;
  7. pid = fork();
  8. if(pid == 0){
  9. printf("child process : %d\n", getpid());
  10. //exit(0);
  11. }
  12. else{
  13. int status;
  14. pid_t waitpid;
  15. printf("parent process : childpid=%d , mypid=%d\n",pid, getpid());
  16. waitpid = wait(&status);
  17. printf("waitpid:%d\n", waitpid);
  18. }
  19. printf("end pid: %d\n", getpid());
  20. return 0;
  21. }

github源代码

例子2:父进程和子进程之间,值是不共有的,你是你的,我是我的。

  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <stdlib.h>
  4. int main(){
  5. pid_t pid;
  6. int i = 100;
  7. pid = fork();
  8. if(pid == 0){
  9. printf("child process : %d\n", getpid());
  10. i += 500;
  11. }
  12. else{
  13. printf("parent process : childpid=%d , mypid=%d\n",pid, getpid());
  14. i += 1024;
  15. }
  16. printf("i=%d\n", i);
  17. return 0;
  18. }

github源代码

例子3:线程之间,值是共有的。

  1. #include <stdio.h>
  2. #include <unistd.h>//sleep function
  3. #include <pthread.h>
  4. int global_val = 0;
  5. void* sub_thread(void *data){
  6. int* val = (int*)data;
  7. printf("sub_thread : val=%d\n", *val);
  8. for(int i = 0; i < 10; ++i){
  9. global_val++;
  10. printf("sub_thread : i=%d, g=%d\n", i, global_val);
  11. sleep(1);
  12. }
  13. return NULL;
  14. }
  15. int main(){
  16. pthread_t th;
  17. void* th_ret;
  18. int arg = 200;
  19. if(pthread_create(&th, NULL, sub_thread, (void*)&arg) != 0){
  20. perror("pthread_create");
  21. return 1;
  22. }
  23. for(int i = 0; i < 10; ++i){
  24. global_val++;
  25. printf("main: i=%d, g=%d\n", i, global_val);
  26. sleep(1);
  27. }
  28. if(pthread_join(th, &th_ret) != 0){
  29. perror("pthread_join");
  30. return 1;
  31. }
  32. return 0;
  33. }

github源代码

编译时需要加 -pthread

  1. g++ -g process-5-thread.cpp -std=c++11 -pthread

c/c++ 学习互助QQ群:877684253

本人微信:xiaoshitou5854

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号