fork() in for() loop

て烟熏妆下的殇ゞ 提交于 2019-12-23 09:36:55

问题


I'm trying to make a homework assignment where I have to use fork() but I don't know why I can't stop my forks after running them through my for loop:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

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 created\n");
            exit(1);
        }
        if(fork()==0){
            printf("fork: %d \n",i);
            exit(1);
        }
        wait(0);
    }


    printf("exiting...\n");
    return 0;
}

Output:

warzaru@ubuntu:~/OS/UprocH$ ./exe a b c d
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...

回答1:


Daniel Fischer forced me to provide an answer.

Change:

if(fork()==-1){} // first fork
if(fork()==0){}  // second fork

To:

pid = fork();
if(pid == -1)
{
    ... //failed
}
else if(pid == 0)
{
    ... //success
}

Or use a switch statement:

switch(fork())
{
    case -1:
        ... // failed
        break;
    case 0:
        ... // success
        break;
}



回答2:


You could use execl() or some other variant of exec, this ensures that the child being created does not inherit anything from the parent. This would allow you to create children with a for loop without going into an exponential child explosion. Modify the arguments of the execl function suitably and you can create 3 processes like:

main()
{
    int i,pid[3];
    for(i=0;i<3;i++)
    {
        pid[i]=fork();
        if (pid[i]==0)
            execl("path",0,0);
    }

    sleep(2);
}


来源:https://stackoverflow.com/questions/10439426/fork-in-for-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!