在C中使用管道

在C中使用管道,c,pipe,C,Pipe,我编写了以下代码来帮助我理解管道在C中是如何工作的 #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <errno.h> struct sum_ { int a; int b; }; int main (void) { int pipe1[2]; int pid; st

我编写了以下代码来帮助我理解管道在C中是如何工作的

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>

struct sum_ {
    int a;
    int b;
};

int main (void) {
    int pipe1[2];
    int pid;
    struct sum_ sum;

    if ( (pipe(pipe1) != 0)){
        printf("pipe(): %d %s\n", errno, strerror(errno));
        exit(1);
    }

    pid = fork();
    if (pid == -1) {
        printf("fork(): %d %s\n", errno, strerror(errno));
        exit(1);
    }
    else if (pid == 0) { // Child
        close(pipe1[0]);

        sleep(5);
        sum.a = read(pipe1[0], &sum.a, sizeof(sum.a));

        printf("Your number was: %d", sum.a);
    }
    else { // Father
        close(pipe1[1]);

        printf("\nWrite a number: \n");
        char a[4];
        sum.a = atoi(fgets(a, 4, stdin));

        write(pipe1[1], &sum.a, sizeof(sum.a));
    }

    return 0;
}
#包括
#包括
#包括
#包括
#包括
结构和{
INTA;
int b;
};
内部主(空){
int-pipe1[2];
int-pid;
结构和uusum;
如果((管道(管道1)!=0)){
printf(“pipe():%d%s\n”,errno,strerror(errno));
出口(1);
}
pid=fork();
如果(pid==-1){
printf(“fork():%d%s\n”,errno,strerror(errno));
出口(1);
}
如果(pid==0){//Child
关闭(管道1[0]);
睡眠(5);
sum.a=读取(pipe1[0],&sum.a,sizeof(sum.a));
printf(“您的号码是:%d”,sum.a);
}
否则{//父亲
关闭(管道1[1]);
printf(“\n写一个数字:\n”);
chara[4];
总和a=原子(fgets(a,4,stdin));
写入(pipe1[1],&sum.a,sizeof(sum.a));
}
返回0;
}
代码有一个父进程和一个子进程。这很简单,父亲使用管道将数字发送给儿子,儿子则为用户显示数字。 结果我总是得到-1分。我做错了什么

 close(pipe1[0]);

 sleep(5);
 sum.a = read(pipe1[0], &sum.a, sizeof(sum.a));
关闭文件描述符
pipe1[0]
,然后从中读取(并返回get-1)。你在父亲身上也犯了同样的错误。我想你的意思是在这里关闭
pipe1[0]
,在父亲那里关闭
pipe1[1]


此外,当您修复该问题时,尽管您正在读取sum.a,但通过传递地址,您也在从返回值进行设置,这将覆盖您读取的内容

你没有说你从哪里得到
-1
。还请注意,您正在使用返回值
read()
覆盖
sum.a
,因此在成功的情况下,您将只打印sum.a的大小。如果您要
关闭(管道[0])
,那么您应该从
管道[1]
,而不是从
管道[0]
,因为您刚刚关闭了后者。
write()
调用也是如此。