I wrote a small TCP servers with socket()
+ POLLIN poll()
+ recv()
+ send()
, but I don't know when to use POLLOUT poll or select writefds
to poll on writable event.
Can anyone give me an example of the real usage of POLLOUT?
The poll() function shall identify those file descriptors on which an application can read or write data, or on which certain events have occurred. Data other than high-priority data may be read without blocking. For STREAMS, this flag is set in revents even if the message is of zero length.
The poll() function is used to enable an application to multiplex I/O over a set of descriptors. For each member of the array pointed to by fds, poll() will examine the given descriptor for the event(s) specified. nfds is the number of pollfd structures in the fds array.
From Linux documentation, POLLOUT means Normal data may be written without blocking.
poll is a POSIX system call to wait for one or more file descriptors to become ready for use. On *BSD and macOS, it has been largely superseded by kqueue in high performance applications. On Linux, it has been superseded by ppoll and epoll.
From nginx source, I found that:
If there is some data to send out, nginx tries to send it with a syscall (maybe writev). However, if nginx can not send total data at one time, it will set POLLOUT on pollfd, if using poll event, to wait for a writable event. When getting a writable event, nginx will send the left data.
It is easy to reproduce this case when nginx tries to response large static file
The usual pattern is to use non-blocking file descriptors with poll()
like this:
poll()
,
POLLIN
because you are always interested in reading what the other end of the socket has send you.
POLLOUT
only if you have outstanding data to send to the other end.poll()
, if it indicates that data is available to read,
poll()
, if it indicates that the socket is writable,
POLLOUT
next time through the loopPOLLOUT
the next time through the loop.POLLOUT
the next time through the loop only if there was some data left.POLLOUT
the next time through the loop. (This choice is often easier to program because you only need to handle writing data in one place in your loop but on the other hand it delays writing the data until the next time through the loop.)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With