tags:

views:

618

answers:

2

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

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

Untested, but hope this helps. :-)

Chris Jester-Young
It didn't. It gave me error
chappar
Chis, I get error EINVAL. The int oldflag is fine.
chappar
Chris Jester-Young
According to the IEEE Std 1003.1, 2004 Edition on fcntl (http://www.opengroup.org/onlinepubs/009695399/functions/fcntl.html), fcntl with command F_GETFL returns on successful completion "Value of file status flags and access modes. The return value is not negative." Thus, oldfl is never -1.
Daniel Trebbien
A: 

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).

codelogic
Unsetting all flags is a bit overkill if you just want to unset the nonblocking flag. :-)
Chris Jester-Young
True, was only curious to know if it was working at all :)
codelogic