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);
Use select() or epoll(). This is the standard way to achieve nonblocking reads (or writes) without multi-threading.