gpt4 book ai didi

c - 管道中传输的数据是垃圾

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

我正在使用 this 的这两个程序回答。这个答案使用命名管道而不是管道,我说得对吗?

我写了 main.c,它实际上是我实际项目的代码,最小化到这个特定问题(这就是为什么我有一个 for 循环的原因)。

#include <unistd.h>
#include <sys/wait.h>
#include <stddef.h>
#include <limits.h>
#include <stdio.h>


int main(void) {
pid_t pid;

int i;
for(i = 0; i < 2; ++i) {
pid = fork();
if (pid == -1) {
// error, failed to fork()
perror("failed to fork()");
return 1;
} else if (pid == 0) {
// child code
if(i < 1) {
// the writer.c
char* arg_list[] = { "w", NULL };
execv( "w", arg_list );
printf("exec FAILED\n");
} else {
// the reader.c
char* arg_list[] = { "r", NULL };
execv( "r", arg_list );
printf("exec FAILED\n");
}
}
}

// parent code
int status;
// wait for all children to terminate
while ((pid = wait(&status)) > 0) {
if (status == 1) {
printf("The child process terminated with an error!\n");
return -1;
}
}
printf("All children are done\n");

return 0;
}

问题是,有时,读取器会收到垃圾(或者很可能什么也没有)然后挂断。

示例输出:

Received: Hi
All children are done
samaras@samaras-A15:~/test$ ./m
Received: Hi
All children are done
samaras@samaras-A15:~/test$ ./m
Received: <----------------- This is garbage, that is not reproducible
^C

那么,我错过了什么?

无需阅读该点以下内容。


我的猜测是(没有检查,所以如果我是正确的,我仍然需要澄清):

reader 在 writer 之前运行,这就是为什么它有垃圾,但为什么它会挂起?

我需要编写一个包装器函数 read_all()(还有一个用于 write case 吗?)来收集管道吐出的所有数据,但是为什么我要替换“Hi”用“H”,我有同样的行为?


编辑:

以防我的第一个猜测是这种情况,我设置了一个读取循环,但在读取器先启动的情况下它将永远执行。

在我看到垃圾的情况下,在使用 strace -f 运行后我得到了这个:

...
[pid 3326] read(-1, 0xbfddd80c, 1024) = -1 EBADF (Bad file descriptor)^C
Process 3324 resumed
Process 3325 detached
Process 3326 detached

最佳答案

您的循环(或缺少循环)与它无关。当您的读者在编写者创建管道之前打开 (open()) 用于读取的管道时,那么您的读者等待的文件描述符是无效的 (-1)。所以即使 writer 稍后写了一些东西,reader 也只是等待一个无效的 fd (-1) 并且永远不会读取任何东西。平凡地,你可以解决它:

while( (fd = open(myfifo, O_RDONLY)) == -1); 

在阅读器中等待管道可用。我实际上想知道是否有比这更好的方法。我能想到的另一种方法是在 access() 上循环,但它与这个并没有太大的不同......

关于c - 管道中传输的数据是垃圾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26938571/

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