gpt4 book ai didi

c - 在 C 语言中使用管道

转载 作者:太空宇宙 更新时间:2023-11-04 08:40:44 24 4
gpt4 key购买 nike

我编写了以下代码来帮助我理解管道在 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;
}

代码有一个父子进程。很简单,父亲用管道发送一个数字给儿子,儿子给用户显示这个数字。结果我总是得到-1。我做错了什么?

最佳答案

 close(pipe1[0]);

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

您关闭文件描述符 pipe1[0],然后从中读取(因此返回 -1)。你在父亲身上也犯了同样的错误。我想你的意思是关闭 pipep1[0] 这里和 pipe1[1] 在父亲

另外,当你解决这个问题时,虽然你是通过传递地址读入 sum.a,但你也在从返回值中设置它,这将覆盖你读到的内容。

关于c - 在 C 语言中使用管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23697620/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com