从管道读取被阻塞
我正在从管道中读取未知数量的消息。但是,读取是阻塞的。我尝试使用下面的代码将读取设置为非阻塞。然而,这会导致读取错误并且进程无法完全读取。
// Set pipe to non-blocking
sleep(5);
fcntl(fd[index][0], F_SETFL, O_NONBLOCK);
如何在程序不挂起的情况下成功读取并打印所有消息? 这是导致问题的代码:
// Read every message
while((n = read(fd[index][0], &mymsg, sizeof(int))) == sizeof(int))
printf("process%d has received a message from process%d\n", index, mymsg);
I'm reading an unkown number of messages from a pipe. However, read is blocking. I've tried the below code to set the reads to non-blocking. However, this resulted in read errors and processes not reading all the way through.
// Set pipe to non-blocking
sleep(5);
fcntl(fd[index][0], F_SETFL, O_NONBLOCK);
How can I successfully read and print all the messages, without the program hanging?
Here is the code that causes the issue:
// Read every message
while((n = read(fd[index][0], &mymsg, sizeof(int))) == sizeof(int))
printf("process%d has received a message from process%d\n", index, mymsg);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 select() 或 epoll()。这是无需多线程即可实现非阻塞读取(或写入)的标准方法。
Use select() or epoll(). This is the standard way to achieve nonblocking reads (or writes) without multi-threading.