Reputation: 51
I have to write program that performs operations based on data received by udp sockets and which must to write data to pipe whenever its possible(by possible i mean that there is enough space in pipe). Pipe is blocking, in fact it is stdout.
Without writing behavior i would write something like this:
while(true) {
if (poll(poll_fd, n, -1) > 0) {
if (poll_fd[0].revents & POLLIN) {
poll_fd[0].revents = 0;
handle_read();
}
/* handlers for other read descriptors ... */
} else {
perror("poll");
exit(1);
}
}
How can i add to program writing behavior?
Poll on write could tell only that writing one byte will no block, and writing only one byte per time isn't very effective. As far as i know i couldn't set file flag to non blocking because it would leeks to other programs that read from that pipe(it changes file description, not file descriptor).
Upvotes: 1
Views: 588
Reputation: 14187
As you point out, poll()
will tell you if at least one byte is writeable without blocking. The pipe may be able to accept more bytes, but you can't really tell until you do the write operation.
If the pipe is set to non-blocking, write()
will write as many bytes as it can, and return the number of bytes actually written.
And then you've got to keep track of things for the next opportunity the pipe is writable. If you've got (say) 1000 bytes to write, and the write operation only accepts (say) 250, then you've got to advance ahead in your buffer by 250 bytes and try writing the remaining 750 bytes when the pipe is writable again.
Upvotes: 1