管道不可读 c
我正在编写一些涉及管道的代码。这个想法是,我应该有一个无限循环的进程,并将数据添加到管道中(我通过读取文件并在 while 循环中逐行进行测试)。
如果我将另一个进程(读取管道的进程)设置为睡眠状态,以便读取整个文件,我就没有问题并在输出中获取所有文件。一旦我取消睡眠(所以现在两个进程同时启动,第二个进程从管道中读取信息),我的代码就会直接进入下面代码的 else 块,我永远不会看到任何实际输出。我做错了什么?
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);
}
}
谢谢
I'm working on some code involving pipes. The idea is that I'm supposed to have a process looping indefinitely and add data to the pipe as it comes (I'm testing this by reading a file, and going line by line in a while loop).
If I set the other process (the one that reads the pipe) to sleep so the entire file is read I have no problems and get all the file in the output. As soon as I remove the sleep (so now the 2 processes start simultaneously with the 2nd process reading the information off the pipe as it comes), my code goes straight to the else block of my code below and I never see any actual output. What am I doing wrong?
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);
}
}
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
两件事:
可能 errno 第一次是 EWOULDBLOCK,然后在成功读取时不会更新,所以它看起来又像 EWOULDBLOCK。
Two things:
int nbio=1; ioctl(pipe[0], FIONBIO, &nbio);
probably errno is EWOULDBLOCK the first time through, and then doesn't get updated on successful read, so it looks like EWOULDBLOCK again.