Linux中fcntl函数中F_GETFD、F_SETFD和F_SETFL、F_GETFD的使用问题

10 篇文章 0 订阅

问题描述:在学习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手册上写的

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值