c - 从管道读取出错
问题描述
我想从管道中读取整数然后打印它,但每次它都会打印垃圾值。有人可以帮助我吗?
int main()
{
int pid1 = fork();
int fd1[2];
pipe(fd1);
if (pid1 == 0) // Child process
{
int x;
close(fd1[1]);
read(fd1[0], &x, sizeof(int));
printf("I'm the First Child and I received: %d\n", x); // <--- Here it prints garbage value
close(fd1[0]);
}
else // Parent process
{
int x = 5;
close(fd1[0]);
write(fd1[1], &x, sizeof(int));
close(fd1[1]);
}
}
解决方案
我必须fork()
在创建管道之后。所以代码看起来像这样:
int main()
{
int fd1[2];
pipe(fd1);
int pid1 = fork();
if (pid1 == 0) // Child process
{
int x;
close(fd1[1]);
read(fd1[0], &x, sizeof(int));
printf("I'm the First Child and I received: %d\n", x);
close(fd1[0]);
}
else // Parent process
{
int x = 5;
close(fd1[0]);
write(fd1[1], &x, sizeof(int));
close(fd1[1]);
}
}
推荐阅读
- python-3.x - 'chromium-browser' 不是内部或外部命令、可运行程序或批处理文件
- daml - 如何在没有互联网连接的 Ubuntu VM 中安装 DAML SDK?
- javascript - 小屏幕上的引导日期选择器问题
- c# - Unity 中的四元数
- html - thymeleaf 中的嵌套迭代无法正常工作
- r - 用于R中的多个变量的glm
- javascript - 构建 OpenCV.js 失败。CMake 找不到已安装的编译器?
- javascript - 如何解决此错误:找不到模块'import-local'
- wcf - 在 WCF 中启用了 Cors,但在实时服务器上不起作用
- web-scraping - 为什么 BeautifulSoup 在使用 findAll 时会跳过一些表