为什么我得到了大量的收获?

时间:2016-05-28 05:57:08

标签: c fork posix

我正在处理一个类的项目,它应该从命令行中获取数字,fork,然后将它们传递给子进程添加,然后父进程应该获取数字的总和。它似乎工作得很好,除非我收获子进程时它给了我大数而不是它最初加在一起的数字之和。如果我只是输入0,我得到0,如果我输入1,我得到256,依此类推。我错过了什么,我只是没有正确收获?感谢。

enter code // Numbers from command line arguments are sent to child process
// from parent process one at a time through pipe.
//
// Child process adds up numbers sent through pipe.
//
// Child process returns sum of numbers to parent process.
//
// Parent process prints sum of numbers.


static int  com[2];

int main(int argc, char **argv)
{
    pid_t   pid;

    // set up pipe

    if (pipe(com))
    {
       printf("pipe error\n");
       return -1;
     }

    //call fork()

    pid = fork();

    if (pid == 0)
    {
        // -- running in child process --

        int             sum = 0;
        int             input = 0;

        //close output end of pipe

        close(com[1]);

        // Receive characters from parent process via pipe
        // one at a time, and count them.

        for (int idx = 1; idx < argc; idx++) //stared idx at 1 instead of 0
        {
                read(com[0], &input, 4); //changed from 4
                sum = sum + input;
        }
                printf("child sum: %i \n", sum); // error checking

        // Return sum of numbers.

        return sum;
    }
    else {
            // -- running in parent process --

            int sum;

            //close output end of pipe

            close(com[0]);

            // Send numbers (datatype: int, 4 bytes) from command line arguments
            // starting with argv[1] one at a time through pipe to child process.

            for (int idx = 1; idx < argc; idx++)
            {
                    int output = 0;

                    output = atoi(argv[idx]);
                    write(com[1], &output, 4);
                    printf("output: %i \n", output);// error checking
            }

            close(com[1]);

            // Wait for child process to return. Reap child process.
            // Receive sum of numbers via the value returned when
            // the child process is reaped.

            waitpid(pid, &sum, 0);

            printf("sum = %d\n", sum);

            return 0;
       }
 }

这里

1 个答案:

答案 0 :(得分:4)

来自man page

  

如果status不为NULL,则wait()和waitpid()将状态信息存储在它指向的int中。可以使用以下宏检查此整数

其中两个是

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>SimpleServletProject_6_passing_more_parameters</display-name>

</web-app>