c - fcntl() 的返回值带有 F_GETFD 标志?

标签 c linux sockets select fcntl

我通过以下调用在文件描述符上使用 fcntl() :

Retval = select(
    MaxSocketId + 1,
    &ReadSocketSet,
    (fd_set *)NULL,
    (fd_set *)NULL,
    (struct timeval *)NULL
);

if (Retval <= 0) {
    for (lIndexFD = 3; lIndexFD < (MaxSocketId + 1); lIndexFD++) {
        if ((lFlag = fcntl(lIndexFD, F_GETFD)) < 0) {
            if (errno == 9) {
                FD_CLR(lIndexFD, &ActiveSocketSet);
            }
        }
        else
            printf(" \n In fcntl Else cond %d ", lFlag);
    }
    continue;
}

但我的进程在 fcntl() 的 else 条件下进入无限循环。看起来 fcntl() 正在返回 0。

我想知道它在什么情况下返回 0 以及如何处理这种情况。

最佳答案

更新:

if (Retval <= 0)可能会更改为 if (Retval < 0) .

Retval为零,select运行正常。

Retval是 -1 并且 errno 是 EBADF , 然后使用 fcntl 检查 fd 是否有效。

你看过 fcntl 它总是返回 0,那是因为:

  1. 没有设置 fd 的 FD_CLOEXEC旗帜

  2. select不会失败,fcntl 也不会失败,因为所有的 fd 都是有效的。


fcntl有很多种cmd .使用 F_GETFD 时,这意味着检索文件描述符标志。

检查 fcntl的手册,此类型中只有一个标志(FD_CLOEXEC)。因此,如果不为 fd 设置此标志,则 F_GETFD将返回值 0。

File descriptor flags

The following commands manipulate the flags associated with a file descriptor. Currently, only one such flag is defined: FD_CLOEXEC, the close-on-exec flag. If the FD_CLOEXEC bit is 0, the file descriptor will remain open across an execve(2), otherwise it will be closed.

  F_GETFD (void)
         Read the file descriptor flags; arg is ignored.

  F_SETFD (int)
         Set the file descriptor flags to the value specified by arg.

什么时候不返回0?

  1. open一个文件,标志FD_CLOEXEC默认禁用。您可以像这样启用它。

    fd = open(filepath, O_RDONLY | O_CLOEXEC)
    
  2. 调用fcntl(fd, F_SETFD, FD_CLOEXEC)启用标志 FD_CLOEXEC .

关于c - fcntl() 的返回值带有 F_GETFD 标志?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53058178/

相关文章:

c - 如何从 IAR EWARM 中的内联汇编器调用另一个模块中的 C 函数?

c - 计数器值小于访问次数的网页计数器

linux - 使用 Eclipse 从 Portaudio 编译 paex_record_file.c 时未定义对 `PaUtil_GetRingBufferReadAvailable' 的引用

linux - 如何在Linux系统中创建/访问共享文件夹?

C : scanf and whitespaces. 我已经尝试了几乎所有的东西,目前正在学习结构

C - 使用自由函数时程序崩溃

linux - 如何在 docker 中成功启用 udev 同步?

java - Netty 服务器不关闭/释放套接字

actionscript-3 - Air-As3 套接字关闭套接字停止发送信息

ios - Nodejs - 如何使用 socket.io 获取 url 参数?