C:使用Fork()和Pipe()在子进程中添加数字

时间:2016-03-08 21:11:42

标签: c pipe fork

我尝试将文件中的数字发送到具有PartialOrdfork()的子进程,子进程应该添加并发送回父进程,然后父进程将添加子进程得到一笔总和。

对于该问题的简化版本,我有一个包含4个数字的数组,并且只使用了1个子进程(2个管道)。

我很难看到程序中的控制权在哪里,这使我很难解决其他问题。

pipe()

}

我的输出如下:

int main(int argc, char *argv[])
{
int numChildProcesses = 1;
int testArray[4] = {2,7,9,4};

printf("Will use 1 child process; %d pipes.\n", numChildProcesses*2);
int fd[numChildProcesses*2][2]; //parent and child

int val = 0, len, i;

// create all the descriptor pairs we need
for (i=0; i<numChildProcesses*2; ++i) // 2 pipes // parent + child
{
    if (pipe(fd[i]) < 0)
    {
        perror("Failed to allocate pipes.");
        exit(EXIT_FAILURE);
    }
}

for (i=0;i<numChildProcesses;i++)
{

    //CHILD/////////////////////////////////////////////////////////////////////
    if (fork() == 0)
    {
        int total = 0, xCount = 0;

        while (xCount < 4)
        {
            // wait for parent to send us a value
            len = read(fd[i][0], &val, sizeof(val));
            if (len < 0)
            {
                perror("Child: Failed to read data from pipe.\n");
                exit(EXIT_FAILURE);
            }
            else if (len == 0)
            {
                // not an error, but certainly unexpected
                fprintf(stderr, "Child: Read EOF from pipe\n");
            }
            else // Successfully read from Parent
            {
                total += val;
                xCount += 1;
                printf("Child: Recieved %d\tTotal: %d\tCount: %d\n", val, total, xCount);

            }
        }

        // send the value back to the parent
        printf("Child: Sending %d back\n", total);
        if (write(fd[i][1], &total, sizeof(total)) < 0)
        {
            perror("Child: Failed to write response value");
            exit(EXIT_FAILURE);
        }

        return EXIT_SUCCESS;
    }

    //PARENT/////////////////////////////////////////////////////////////////////
    if (fork() > 0)
    {
        int total = 0;

        // send array to child as well as starting point
        printf("\nParent: Sending numbers to child\n");
        //if (write(fd[i][1], 0, (fileNumbers/numChildProcesses)*5) != sizeof((fileNumbers/numChildProcesses)*5));
        if (write(fd[i][1], &testArray, sizeof(testArray)) != sizeof(testArray))
        {
            perror("Parent: Failed to send value to child ");
            exit(EXIT_FAILURE);
        }

        // now wait for a response
        len = read(fd[i][0], &val, sizeof(val));
        if (len < 0)
        {
            perror("Parent: failed to read value from pipe");
            exit(EXIT_FAILURE);
        }
        else if (len == 0)
        {
            // not an error, but certainly unexpected
            fprintf(stderr, "Parent: Read EOF from pipe\n");
        }
        else
        {
            // report what we received
            total += val;
            printf("Parent: Received %d\tTotal: %d\n", val, total);
        }

        // wait for child termination
        wait(NULL);
    }
}

此外,如果我在进入Will use 1 child process; 2 pipes. Parent: Sending numbers to child Parent: Received 2 Total: 2 Child: Recieved 7 Total: 7 Count: 1 Child: Recieved 9 Total: 16 Count: 2 Child: Recieved 4 Total: 20 Count: 3 循环后尝试printf("%d", fork());之类的内容,看看它控制了什么,就会有点疯狂。它就像使用for()一样影响程序的运行方式,就好像它是fork()或类似的东西。

无论如何,感谢您提供的任何见解。

- 汤姆

1 个答案:

答案 0 :(得分:2)

你太过分了。您在循环中两次致电fork():一次在您的孩子身上&#34; if,以及您父母的一个&#34;} if。当你添加printf("%d", fork());时,甚至更多。

每个循环只能调用一次fork()。将返回值保存在变量中,然后打印/检查它。