c - 将整数从父级传递给子级的错误输出

标签 c pipe parent child-process

我的任务是传递在命令行上输入的整数,并通过管道将它们从父级传递到子级,整数可以加在一起并通过收割返回给父级。我所有的整数在 child 中都变成了数字 4,并且 sum 的收获值总是返回数字 1。

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

static int  toChild[2];
static int  toParent[2];
static int  input;
static int  output;

int main(int argc, char **argv)
{
    pid_t   pid;
    int     status;
    int     nInts = argc;
        // set up pipe
    pipe(toChild);
    pipe(toParent);
        // call fork()
    pid = fork();

    if (pid == 0) {
        close(toChild[1]);
        close(toParent[0]);
            // -- running in child process --
        int     sum = 0;
            // Receive characters from parent process via pipe
            // one at a time, and count them.
            // Return sum of numbers.
        for (int i=1; i < nInts; i++) {
            output = read(toChild[0], &input, sizeof(input));
            sum += output;
            }

        return sum;
        close(toChild[0]);
        close(toParent[1]);
        }
    else {
        close(toChild[0]);
        close(toParent[1]);
            // -- running in parent process --
            // 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 i=1; i < nInts; i++) {
            input = atoi(argv[i]);
            write(toChild[1], &input, sizeof(input));
            }

        waitpid(pid, &status, 0);
        if(WIFEXITED(status)){
            // Wait for child process to return. Reap child process.
            // Receive sum of numbers via the value returned when
            // the child process is reaped.
            printf("sum = %d\n", WIFEXITED(status));
        }
        close(toParent[0]);
        close(toChild[1]);
        return 0;
        }
}

最佳答案

output = read(toChild[0], &input, sizeof(input));
sum += output;

您正在将 read 的返回值分配给 output。这是读取的字节数,即 sizeof(input) 在您的平台上为 4。所以你总是将 sum 增加 4。

你想要:

ssize_t bytes_read = read(toChild[0], &input, sizeof(input));
//check that bytes_read == sizeof(input) here
sum += input;

还有:

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

WIFEXITED 只是表示进程是否退出。使用 WEXITSTATUS 获取退出状态。

关于c - 将整数从父级传递给子级的错误输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45655618/

相关文章:

linux - 我怎样才能让 bash 阻止从我产生的工作中获取一行标准输出

javascript - 如何在 Sapper 中离开父布局?

c - 如何使用 C API 检查 SQLite 列中的值是否为 NULL?

c - execve 和管道问题 - 如何恢复原始管道?

c - 段错误: 11 - Simple linked list c

sql - 在swift中通过命令行重建SQL数据库

qt - 将父级传递给 Qt 类构造函数的目的是什么?

javascript - jquery - 如何检查父元素是 tbody 还是 thead?

c++ - 为什么 KCacheGrind 不显示我的函数名称?

c - 告诉 sscanf 将\0 视为要读取的有效字符