Vlad Fedyaev
Vlad Fedyaev

Reputation: 115

pselect() with accept() in a loop

I have a multi-threaded server, which spawns new threads with these loop:

 while(handle->m_run) {
    if (handle->m_curThreadCount < handle->m_maxThreads) {
      ready = pselect(socket + 1, &readSocket, NULL, NULL, &timeout, NULL);
      if (ready != 1)
        continue;
      DWORD openedSocket = accept(socket, NULL, NULL);
      handle->m_threads.emplace_back(std::thread(serverThread, openedSocket, handle));
      handle->m_curThreadCount++;
    }
  }

Most of the time this works as intended, but occasionally pselect() doesn't fire. I checked it with tcpdump and know, that data is sent to server, so I think it has something to do with main loop.

Also, if run with gdb and broken on pselect() before sending data, pselect() returns 1 as intended.

Is there something wrong with using pselect() this way and how should I fix this?

Upvotes: 0

Views: 593

Answers (1)

Vlad Fedyaev
Vlad Fedyaev

Reputation: 115

As Jeremy Friesner said, I did not reset fd_set after pselect() had timed out.

Linux Programmer's manual vaguely states:

On exit, the sets are modified in place to indicate which file descriptors actually changed status.

Adding:

FD_ZERO(&readSocket)
FD_SET(socket, &readSocket)

before pselect() call solved it.

Upvotes: 1

Related Questions