Using poll function with buffered streams

There seem to be two problems in your code. “stdout” is by default buffered,
so the server should flush it explicitly:

printf("I received %s\n", buffer);
fflush(stdout);

And the main program should not register for POLLOUT when trying to read
(but you may want register for POLLERR):

pfds[0].fd = rpipe[0];
pfds[0].events = POLLIN | POLLERR;

With these modifications you get the expected output:

$ ./main
Writing data...
Reading data...
child says:
I received hello

Generally, you should also check the return value of poll(), and repeat the call if
necessary (e.g. in the case of an interrupted system call or timeout).

Leave a Comment