Spectrum01
Spectrum01

Reputation: 31

How poll() function works in C/C++?

My main question is actually to understand the background and usage of the poll function. While writing a simple server-client irc program to learn, I'm stuck the usage of poll and it's event flags. what I've understood so far from man page is poll function circulating in “pollfd ”s in order and blocks the program until there is a action in fd that we specify in events variable. I assume something like;

clientPollFd.events = POLLIN | POLLHUP | POLLERR;

And if there was a action I should(?) check it like this;

if (this->_sockets[i].revents & POLLHUP)

Although I'm confused about how it does background checks and how it controls events (or changes in fd idk), I also have a more practical problem.

When I tried to trigger POLLHUP from client(netcat) with ctrl+c or netcat's -q/-w flags on server but I kept triggering POLLIN or I tried to change directly clientfd or read/write of clientfd to trigger errors flags but I couldn't.

Upvotes: 3

Views: 157

Answers (1)

Swift - Friday Pie
Swift - Friday Pie

Reputation: 14688

poll() documentation regulated not by language's standard but by documentation on OS API. Assuming POSIX-compatible poll...

Note:

   POLLERR, POLLHUP, or POLLNVAL.  (These three bits are
   meaningless in the events field, and will be set in the revents
   field whenever the corresponding condition is true.)

The flags aren't exclusive aso that's not all flags, there is also POLLERR. POLLERR is triggered if a RST was received, i.e. other end decided to drop conection for some reason and "tells" this side "I won't be receiving from you anymore". POLLHUP is triggered after normal close of socket if a FIN was received and sent.

There can be sitaution where it woudn't, especially if it's an TCP going through a NAT routing service with security features or something like that. the signal-ased break you use doesn't result in sending these by default, the handler must close the connection. In your case there is likely POLLIN because there is new data in pipe before pipe was closed.

Upvotes: 3

Related Questions