首页 > 解决方案 > 如何在 C 中获取打开的 fd 的标志?

问题描述

我想获得以前在 C 中打开过的 fd 的标志。

但是我使用fcntl(fd,F_GETFD,0)fcntl 手册页的引用,它总是返回 1 给我。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>

#define XSZ(x) (int)(sizeof(x)*2)

int main()
{
    int ret;
    static const char str [] = "hello c program!\n";
    int fd = open("test.txt", O_RDWR | O_APPEND | O_CREAT, 0777);
    if(fd < 0)
    {
        perror("open");
        return -1;
    }
    printf("fd = %d\n", fd);

    ret = fcntl(fd, F_GETFD, 0);
    printf("flag:%d\n",ret);
    write(fd, str, strlen(str)-1);

    return 0;
}

它总是打印:

fd = 3
flag:1

我认为 ret 是O_RDWR | O_APPEND | O_CREAT

标签: clinuxfcntl

解决方案


F_GETFD不查询打开的标志,而只是FD_CLOEXEC(见这里)。

线

write(fd, "hello c program\n", strlen("hello c program!\n"));

是错误的,因为您查询的字符串长度比您编写的字符串的长度长,可能导致缓冲区溢出。一种更安全、更有效的方法是:

static const char str [] = "hello c program!\n";
write(fd, str, sizeof(str)-1);

-1需要避免写入终止的 0 字节。

我不知道的目的

#define XSZ(x) (int)(sizeof(x)*2)

但是将size_t(的结果类型sizeof())转换int为可能不是一个好主意。


推荐阅读