当前位置:   article > 正文

C++通过fork创建子进程实战_c++子进程示例

c++子进程示例

一 代码

  1. #include <iostream>
  2. using namespace std;
  3. #include <unistd.h>
  4. #include <stdio.h>
  5. int main()
  6. {
  7. pid_t fpid;
  8. int count = 0;
  9. fpid = fork(); //返回子进程的进程ID
  10. if (fpid < 0) //如果返回负数,则出错了
  11. cout<<"failed to fork";
  12. else if (fpid == 0) //如果fork返回0,则下面进入子程序
  13. {
  14. cout<<"I am the child process, my pid is "<<getpid()<<endl;
  15. count++;
  16. }
  17. else //如果fork返回值大于0,则依旧在父进程中执行
  18. {
  19. cout<<"I am the parent process, my pid is "<<getpid()<<endl;
  20. cout << "fpid =" << fpid << endl;
  21. count++;
  22. }
  23. printf("count=%d\n", count);
  24. return 0;
  25. }

二 运行

  1. [root@localhost test]# g++ test.cpp -o test
  2. [root@localhost test]# ./test
  3. I am the parent process, my pid is 995
  4. fpid =996
  5. count=1
  6. [root@localhost test]# I am the child process, my pid is 996
  7. count=1

三 说明

fork函数创建一个子进程。如果成功,在父进程的程序中将返回子进程的进程ID,即PID。子进程在返回0的分支继续运行,父进程在返回子进程号的分支继续运行。如果失败,则在父进程程序中返回-1。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/882972
推荐阅读
相关标签
  

闽ICP备14008679号