繁体   English   中英

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

[英]C: Using Fork() and Pipe() to add numbers in child processes

我正在尝试使用fork()pipe()将文件中的数字发送到子进程,子进程应将这些数字相加并发送回父进程,然后再将其与子进程相加以获得总和。

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

我在查看程序中的控制位置时遇到了困难,这使我很难对其他问题进行故障排除。

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()会影响程序的运行方式一样,就像是pop()或类似的东西一样。


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

-汤姆

你太分叉了。 您在循环中两次调用fork() :在“子” if一次,在“父” if 然后,当您添加printf("%d", fork());时,甚至更多printf("%d", fork());

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM