问题描述:在学习apue的时候学到了fcntl函数,然后试着用它来为一个文件描述符添加O_APPEND标志,但是出错了,代码如下:
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
int main(){
int fd = open("input", O_RDONLY);
if(fd < 0)
perror("open failed!");
int val = fcntl(fd, F_GETFD);
if(val < 0)
perror("fcntl failed!");
printf("%d\n", val & O_APPEND);
val |= O_APPEND;
int ret = fcntl(fd, F_SETFD, val);
if(ret < 0)
perror("fcntl F_SETFD failed!");
val = fcntl(fd, F_GETFD);
if(val < 0)
perror("fcntl failed!");
printf("%d\n", val & O_APPEND);
return 0;
}
发现根本没有设置成功,两次的输出都是1
然后问了一下chatgpt之后发现是cmd参数选错了,应该使用F_SETFL和F_GETFL,因为这个是文件状态标志
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
int main(){
int fd = open("input", O_RDONLY);
if(fd < 0)
perror("open failed!");
int val = fcntl(fd, F_GETFL);
if(val < 0)
perror("fcntl failed!");
printf("%d\n", val & O_APPEND);
val |= O_APPEND;
int ret = fcntl(fd, F_SETFL, val);
if(ret < 0)
perror("fcntl F_SETFD failed!");
val = fcntl(fd, F_GETFL);
if(val < 0)
perror("fcntl failed!");
printf("%d\n", val & O_APPEND);
return 0;
}
一般使用F_GETFD和F_SETFD只设置FD_CLOEXEC这个,这是man手册上写的