gpt4 book ai didi

c - 管道不可读 c

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

我正在编写一些涉及管道的代码。我的想法是,我应该让一个进程无限循环,并在数据到来时将数据添加到管道(我正在通过读取文件并在 while 循环中逐行进行测试)。

如果我将另一个进程(读取管道的进程)设置为 sleep 以便读取整个文件我没有问题并在输出中获取所有文件。一旦我删除 sleep (所以现在 2 个进程同时启动,第二个进程从管道读取信息),我的代码直接进入下面代码的 else block ,我再也看不到任何实际输出。我做错了什么?

close(pipe[1]);  
sleep(5);

while (1) {

nbytes = read(pipe[0], buffer, 200);

if(errno != EWOULDBLOCK) {
printf("%s", buffer);
}

else {
printf("I am not blocked here\n");
sleep(1);
}
}

谢谢

最佳答案

两件事:

  1. 你让 pipe[0] 成为非阻塞的了吗?它会像 int nbio=1; ioctl(管道[0], FIONBIO, &nbio);
  2. 您正在检查错误。
if(nbytes > 0) {
/* you may need to null-terminate the input buffer prior to display */
buffer[nbytes] = '\0';
printf("%s", buffer);
}
else if(errno == EWOULDBLOCK) {
printf("I am not blocked here\n");
sleep(1);
}
else {
printf("some other error occurred - if nbytes == 0, then it's EOF.\n");
}

可能 errno 是 EWOULDBLOCK 第一次通过,然后在成功读取时没有更新,所以它看起来又像 EWOULDBLOCK。

关于c - 管道不可读 c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4201400/

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