Linux网络编程--文件属性fcntl函数

这里写图片描述

/*使用fcntl控制文件符*/
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>

int main(void)
{
    int flags = -1;
    int accmode = -1;

    /*获得标准输入的状态的状态*/
    flags = fcntl(0, F_GETFL, 0);
  if( flags < 0 ){
    /*错误发生*/
    printf("failure to use fcntl\n");
    return -1;
  }

  /*获得访问模式*/
  accmode = flags & O_ACCMODE;  
  if(accmode == O_RDONLY)/*只读*/
    printf("STDIN READ ONLY\n");
  else if(accmode == O_WRONLY)/*只写*/
    printf("STDIN WRITE ONLY\n");
  else if(accmode ==O_RDWR)/*可读写*/
    printf("STDIN READ WRITE\n");
  else/*其他模式*/
    printf("STDIN UNKNOWN MODE");

  if( flags & O_APPEND )
     printf("STDIN APPEND\n");
  if( flags & O_NONBLOCK )
     printf("STDIN NONBLOCK\n");

   return 0;
}

这里写图片描述

例子一:使用函数int fcntl(int fd,int cmd);返回值为新的文件描述符

/*使用fcntl修改文件的状态值*/
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>/*strlen函数*/

#define NEWFD 8
int main(void)
{
    char buf[] = "FCNTL";

    int fd = open("test.txt", O_RDWR);
    printf("the file test.txt ID is %d\n",fd);
    /*获得文件状态*/  
    fd = fcntl(fd, F_GETFD);
    printf("the file test.txt ID is %d\n",fd);
    fd = NEWFD;
    /*将状态写入*/
    fcntl(NEWFD, F_SETFL, &fd);

    /*向文件中写入字符串*/
    write(NEWFD, buf, strlen(buf));
    close(NEWFD);

    return 0;
}

例子二:使用函数int fcntl(int fd,int cmd,long arg);返回值为获得的响应标志位
/*使用fcntl修改文件的状态值*/
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>/*strlen函数*/

int main(void)
{
    int flags = -1;
    char buf[] = "FCNTL";

    int fd = open("test.txt", O_RDWR);
    /*获得文件状态*/  
    flags = fcntl(fd, F_GETFL, 0);
    /*增加状态为可追加*/
    flags |= O_APPEND;
    /*将状态写入*/
    flags = fcntl(fd, F_SETFL, &flags);
    if( flags < 0 ){
        /*错误发生*/
        printf("failure to use fcntl\n");
        return -1;
    }
  /*向文件中写入字符串*/
  write(fd, buf, strlen(buf));
  close(fd);

  return 0;
}

/*使用fcntl获得接收信号的进程ID*/
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>

#define NEWFD 8
int main(void)
{
    int uid;    
    /*打开文件test.txt*/
    int fd = open("test.txt", O_RDWR);

    /*获得接收信号的进程ID*/ 
    uid = fcntl(fd, F_GETOWN);
    printf("the SIG recv ID is %d\n",uid);

    close(fd);

    return 0;
}

这里写图片描述

/*使用fcntl设置接收信号的进程ID:1000*/
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>

#define NEWFD 8
int main(void)
{
    int uid;    
    /*打开文件test.txt*/
    int fd = open("test.txt", O_RDWR);  
    /*获得接收信号的进程ID*/ 
    uid = fcntl(fd, F_SETOWN,1000); 
    close(fd);  
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值