简体   繁体   中英

Processes hang on read

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.

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);

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

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

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.

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

fcntl(fd, F_SETFL, O_NONBLOCK);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM