1

我的程序必须创建多个孩子,我从终端获取孩子的数量。然后,我需要将它们分组,每个组都有不同的任务。

我创造了孩子,但问题是我不能给他们分开的任务,我不能区分孩子。我唯一能做的就是,每个孩子都在同一个部分工作(比如打印 pids)。

我怎样才能将它们分开并赋予它们特定的任务?

例如,前 4 个孩子应该调用一个函数,其他 3 个应该打印一些东西,其他 3 个应该写入一个文件等。

    pid_t pid[10];

    pid[0] = fork();
    if(pid[0] > 0)
    {
        for(int i = 0; i < 9; i++)
        {
            if(pid[i] > 0)
            {
                pid[i + 1] = fork();
            }
        }
    }

    for(int i = 0; i < 10; i++)
    {   
        if(pid[i] == 0)
        {
            printf("child %d, parent %d\n", getpid(), getppid());
            exit(1);
        }
    }
4

2 回答 2

1

我认为你应该看看这个fork()函数是如何工作的。这是手册页,这里是有用的答案,这里是有用的教程

当您fork()在代码中使用时,要知道子进程从父进程的位置继续。因此,当您fork()在第一个for循环中调用时,所有子进程都会继续父进程已经开始的循环。我认为这不是您期望的行为。

无论如何,这是解决您问题的可能方法。通过这种方式,您的流程会做一些分成小组的事情。注意exit(0)工作结束时的功能。重要的是要确保每个进程只做它的工作而不是它的父进程的工作:

pid_t pid[10];

for (int i = 0; i < 9; i++)
{
    pid[i] = fork();

    //First group            
    if (pid[i] == 0 && i < 4){
        //Insert here the code for the first group or call a fuction
        exit(0);
    }

    //Second group
    if (pid[i] == 0 && i >=4 && i < 8){
        //Insert here the code for the second group or call a fuction
        exit(0);
    }

    //Third group
    if (pid[i] == 0 && i >=8){
        //Insert here the code for the third group or call a fuction
        exit(0);
    }

    if (pid[i] < 0){
        perror("Something wrong with the fork");
        exit(1);
    }
}
于 2020-05-05T17:45:00.580 回答
0
int flag = 0;
flag |= (fork() == 0) << 0;
flag |= (fork() == 0) << 1;
flag |= (fork() == 0) << 2;
printf("this process works on problem %d\n", flag);
于 2020-05-05T18:11:44.493 回答