¿Por qué la encuesta sigue regresando aunque no hay entrada?
Escribí un pequeño programa de prueba para averiguar cómo hablar conpoll
. Creé tres archivostesta
,testb
,testc
y escribio la cadenahello\n
a la primera Así que, aquí está mi invocación depoll
:
poll(polls.data(),polls.size(),-1)
Según la página del manual, un timeout de-1
debe indicar que el syscall nunca se apaga. Sin embargo, sigue volviendo sin tener nada que leer. Siempre consumo un byte de la entrada y puedo ver elhello\n
siendo impreso, pero la encuesta no se detiene allí. Simplemente sigue fingiendo que hay algo para leer.
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/fcntl.h>
#include <sys/poll.h>
#include <unistd.h>
#include <errno.h>
#include <vector>
#include <map>
#include <string>
#include <iostream>
typedef int fd_t;
int main() {
fd_t const a = open("testa",O_RDONLY);
fd_t const b = open("testb",O_WRONLY);
fd_t const c = open("testc",O_RDWR);
std::map<fd_t,std::string> names{{{a,"testa"},{b,"testb"},{c,"testc"}}};
std::vector<pollfd> polls;
polls.push_back(pollfd{a, POLLIN, 0});
polls.push_back(pollfd{b, 0, 0});
polls.push_back(pollfd{c, POLLIN, 0});
while (poll(polls.data(),polls.size(),-1)) {
for (auto p : polls) {
if ((p.revents & (POLLIN|POLLERR)) == POLLIN) {
std::cout << "{" << p.fd << ", " << p.events << ", " << p.revents << "} ";
char byte;
auto const rr = read(p.fd,&byte,1);
auto const en = errno;
if (rr) {
std::cout << "File " << names[p.fd] << " says something: '" << ((int)byte) << " (" << (((' '<byte) && (byte<127))?byte:'\0') << ")" << "' \n";
} else {
std::cout << "Strange (file " << names[p.fd] << "). errno says " << en << "\n";
}
}
}
}
}
Lo que obtengo es esto:
{3, 1, 1} File testa says something: '104 (h)'
{5, 1, 1} Strange (file testc). errno says 0
{3, 1, 1} File testa says something: '101 (e)'
{5, 1, 1} Strange (file testc). errno says 0
{3, 1, 1} File testa says something: '108 (l)'
{5, 1, 1} Strange (file testc). errno says 0
{3, 1, 1} File testa says something: '108 (l)'
{5, 1, 1} Strange (file testc). errno says 0
{3, 1, 1} File testa says something: '111 (o)'
{5, 1, 1} Strange (file testc). errno says 0
{3, 1, 1} File testa says something: '10 ()'
{5, 1, 1} Strange (file testc). errno says 0
{3, 1, 1} Strange (file testa). errno says 0
{5, 1, 1} Strange (file testc). errno says 0
{3, 1, 1} Strange (file testa). errno says 0
{5, 1, 1} Strange (file testc). errno says 0
{3, 1, 1} Strange (file testa). errno says 0
{5, 1, 1} Strange (file testc). errno says 0
{3, 1, 1} Strange (file testa). errno says 0
{5, 1, 1} Strange (file testc). errno says 0
(repite las dos ultimas lineas para siempre)
Estoy construyendo cong++ -Wall -Wextra -std=c++11 poll.cpp -o poll
en el kernel 3.10-2-amd64.