进程处于读取状态 [英] Processes hang on read

查看:106
本文介绍了进程处于读取状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码通过管道从其他进程读取消息.所有进程都正确打印出所有消息,但是它们将永远不会经过while循环.尝试在Eclipse中进行调试,阅读完所有消息后,它将仅在while循环中停止.

The following code reads messages from other processes through a pipe. All processes correctly print out all the messages, but then they will never proceed past the while loop. Tried debugging in Eclipse, after reading reading all the messages, it will just stop at that while loop.

索引是分配给每个进程的数字.第一个进程的索引== 0. 消息本身只是发送消息的进程的索引.

The index is a number assigned to each process. The first process would have index == 0. The message itself is simply the index of the process sending the 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);

有什么想法会发生这种情况吗?

Any ideas why this would happen?

以下是每个进程如何写入另一个进程:

Here is how each process writes to another:

// Write to other process
if(write(fd[index2][1], &index, sizeof(int)) != sizeof(int))
    sys_error(2);

这完成了五次. fd是每个进程的读写终点表.

This is done five times. fd is a table of read-and-write ends for each process.

推荐答案

在显示更多数据之前,对read()的调用一直处于阻塞状态.从管道的手册页

The call to read() is blocking until more data shows up. From the man page for pipe

如果进程尝试从空管道读取,则read(2)将 直到数据可用为止.如果进程尝试写入 满管道(请参阅下文),然后写入(2)块,直到有足够的数据 已从管道读取以允许完成写入.无阻塞 通过使用fcntl(2)F_SETFL操作来启用I/O O_NONBLOCK打开文件状态标志.

If a process attempts to read from an empty pipe, then read(2) will block until data is available. If a process attempts to write to a full pipe (see below), then write(2) blocks until sufficient data has been read from the pipe to allow the write to complete. Nonblocking I/O is possible by using the fcntl(2) F_SETFL operation to enable the O_NONBLOCK open file status flag.

在打开每个文件描述符之后,在进入while循环之前,请对每个文件进行以下操作:

After you open each file descriptor before you enter that while loop do this to each one:

fcntl(fd, F_SETFL, O_NONBLOCK);

但是,您确实应该阅读阻塞I/O与非阻塞I/O,包括读取管道的手册页,read,fcntl等.

However, you really should read up on blocking vs. non-blocking I/O, including reading the man pages for pipe, read, fcntl, etc.

这篇关于进程处于读取状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆