Question

How do i unset a already set flag using fcntl?

For e.g. I can set the socket to nonblocking mode using

fcntl(sockfd, F_SETFL, flags | O_NONBLOCK)

Now, i want to unset the O_NONBLOCK flag.

I tried fcntl(sockfd, F_SETFL, flags | ~O_NONBLOCK). It gave me error EINVAL

Was it helpful?

Solution

int oldfl;
oldfl = fcntl(sockfd, F_GETFL);
if (oldfl == -1) {
    /* handle error */
}
fcntl(sockfd, F_SETFL, oldfl & ~O_NONBLOCK);

Untested, but hope this helps. :-)

OTHER TIPS

val = fcntl(fd, F_GETFL, 0);
flags = O_NONBLOCK;
val &= ~flags;
fcntl(fd,F_SETFL,val);

If you do like this,The already set O_NONBLOCK will unset. here,flags contains the which flags you want to unset. After finishing the AND(&) operation,again you have to set the flag using the value in val. I hope this will help you.

The following code will unset a flag, for example, the O_NONBLOCK flag:

if ((flags = fcntl(fileno(sockfd), F_GETFL, 0)) < 0) {
    perror("error on F_GETFL");
}
else {
    flags &= ~O_NONBLOCK;
    if (fcntl(fileno(sockfd), F_SETFL, flags) < 0) {
        perror("error on F_SETFL");
    }
    else {
        /* O_NONBLOCK set without errors. continue from here */
        }
}

Regards

Tried unsetting all flags:

fcntl(sockfd, F_SETFL, 0);

Also OR-ing the flags with ~O_NONBLOCK is of no use, you need to AND it, since what you want is to unset the O_NONBLOCK bit(s).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top