linux fcntl - unsetting flag

穿精又带淫゛_ 提交于 2019-12-10 13:51:44

问题


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:


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

Untested, but hope this helps. :-)




回答2:


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.




回答3:


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




回答4:


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



来源:https://stackoverflow.com/questions/388434/linux-fcntl-unsetting-flag

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!