我想要一个父母和四个孩子,创建之后我会打印如下内容:

 [PID] (parent) with child processes: [PID1] [PID2] [PID3] [PID4]

家长们等着他们全部结束。
我可以在循环中使用这个代码(How to use Fork() to create only 2 child processes?)吗?
我做到了:
      main()
{
    int pid, state, loop1=4, loop2, i=1, j;
    printf(" Parent before fork()\n");
    if ( ( pid=fork() ) !=0)
    {
        ParentPID=pid;
        wait( &state);
    }
    else
    {
        while(loop1!=0)
        {
            execl("child", 0);
            a[i]=pid;
            loop1--;
            i++;
        }
    }
    printf("Parent after fork()\n");
    for ( j=1; j<i; ++j )
    {
        printf ("PARENT_PID:"%d"  CHILD_PID[" %d "]= "%d,ParentPID, j, a[i]);
    }
    //printf("\tId process child=%d; finished with %d=%x\n",pid,state,state);
}

main()
{
    int pid;
    printf("Child: the execution starts \n");
    pid=getpid();
    printf("Child: %d execution finished\n", pid);
    exit( pid);
}

最佳答案

解决办法可以是:

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

void childFunction(){
    printf("Child : %d\n", getpid());
    // do stuff
}

int main(){
    int childLimit = 3; // number of children wanted
    int childrenPids[childLimit]; // array to store children's PIDs if needed
    int currentPid, i;

    for(i=0; i<childLimit; i++){
        switch(currentPid = fork()){
            case 0:
                // in the child
                childFunction();
                // exit the child normally and prevent the child
                // from iterating again
                return 0;
            case -1:
                printf("Error when forking\n");
                break;
            default:
                // in the father
                childrenPids[i] = currentPid; // store current child pid
                break;
        }

    }

    printf("Father : %d childs created\n", i);

    // do stuff in the father

    //wait for all child created to die
    waitpid(-1, NULL, 0);
}

有关更多信息,请参见man waipid;)

关于c - 如何为同一父级创建4个子进程并等待4个子进程完成?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36418368/

10-09 17:06