c - 如何在 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
解决方案
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
为可能不是一个好主意。
推荐阅读
- fuse - 有什么方法可以告诉 getAttr 位于路径的最后一个元素?
- regular-language - 这个带有抽引引理(非常规语言)的证明可以吗?
- amazon-web-services - 如何创建允许经过身份验证的用户将文件上传到 S3 的 Web 表单?
- javascript - 三.JS:使用透明MeshPhongMaterial进行奇怪的闪烁/渲染
- javascript - 如何使用 Firebase 数据库更改文本?
- python - 查找标签内容后出现问题,无法求和
- excel - 如何按属性聚合数据(大数据集)?
- performance - 通过 GraphQL 减少从 API 返回的数据大小?
- xslt - 颠倒 XML 过时程序的顺序
- reactjs - 运行命令 npm start 后,如何在开发模式下(而不是从本地路由)启动特定路线上的反应应用程序