我正在尝试做一个家庭作业,我必须使用fork()
但我不知道为什么在通过我的for循环运行它们之后我无法阻止我的for:
#include #include #include #include #include int main(int argc, char *argv[]){ int limit = argc/2; if(argc%2 == 0){ perror("the number of arguments given must pe even!"); exit(1); } int i; for(i=0; i<=limit; i++){ if(fork()==-1){ perror("childes couldn't be createdn"); exit(1); } if(fork()==0){ printf("fork: %d n",i); exit(1); } wait(0); } printf("exiting...n"); return 0; }
输出:
warzaru@ubuntu:~/OS/UprocH$ ./exe abcd fork: 0 fork: 0 fork: 1 fork: 1 fork: 1 fork: 2 fork: 2 fork: 1 fork: 2 exiting... exiting... fork: 2 exiting... exiting... fork: 2 exiting... exiting... exiting... warzaru@ubuntu:~/OS/UprocH$ fork: 2 fork: 2 fork: 2 exiting...
Daniel Fischer强迫我提供答案。
更改:
if(fork()==-1){} // first fork if(fork()==0){} // second fork
至:
pid = fork(); if(pid == -1) { ... //failed } else if(pid == 0) { ... //success }
或者使用switch语句:
switch(fork()) { case -1: ... // failed break; case 0: ... // success break; }
您可以使用execl()或exec的其他变体,这可以确保正在创建的子级不会从父级inheritance任何内容。 这将允许您创建具有for循环的子项而不会进入指数子爆炸。 适当地修改execl函数的参数,你可以创建3个进程,如:
main() { int i,pid[3]; for(i=0;i<3;i++) { pid[i]=fork(); if (pid[i]==0) execl("path",0,0); } sleep(2); }
以上就是c/c++开发分享for()循环中的fork()相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/c-cdevelopment/545914.html