Switch a fd between blocking and non-blocking mode?

Jeffrey Walton noloader at gmail.com
Mon Nov 11 18:21:01 EST 2019


Hi Everyone,

I have one more question related to my problem of my program losing
data. I want to ensure I'm not using an anti-pattern that's causing
the problem.

I have a worker thread that blocks on read(2). When the read() occurs,
the fd is switch from blocking to non-blocking. Additional reads are
performed until EAGAIN or EWOULDBLOCK. Then the fd is switched back to
blocking mode.

Does switching a socket between blocking and non-blocking mode cause
the kernel to reset or delete queued data (that has not been read by
the application yet)?

Thanks in advance.

Jeff

----------

Here are the functions that switch between blocking and non-blocking
mode. There's not much to them.

void make_blocking_fd(int fd)
{
    const int old = fcntl(fd, F_GETFL, 0);
    fcntl(fd, F_SETFL, old & ~(int)O_NONBLOCK);
}

void make_nonblocking_fd(int fd)
{
    const int old = fcntl(fd, F_GETFL, 0);
    fcntl(fd, F_SETFL, old | (int)O_NONBLOCK);
}



More information about the Kernelnewbies mailing list