您的位置:首页 > 运维架构 > Linux

linux学习笔记(5):dup,dup2,fcntl

2016-06-01 08:33 477 查看
代码先上:
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<stdlib.h>
/*自定义错误处理函数*/
void my_err(const char * err_string,int line)//错误处理函数学习笔记三中有记录
{
fprintf(stderr,"line:%d",line);
perror(err_string);
exit(1);
}
int main()
{
int ret;
int access_mode;
int fd;
if((fd=open("example_64",O_CREAT|O_TRUNC|O_RDWR,S_IRWXU))==-1){  //以读写打开example_64文件,如果不存在则创建,如果存在则把内容清空,用户
my_err("open",__LINE__);                                     //权限可读可写可执行,打开失败则调用错误处理函数
}
/*设置文件打开方式*/
if((ret=fcntl(fd,F_SETFL,O_APPEND))<0){
my_err("fcntl",__LINE__);
}
/*获取文件打开方式*/
if(ret=fcntl(fd,FGETFL,0))<0){
my_err("fcntl",__LINE__);
}
 access_mode=ret&O_ACCMODE;
if(access_mode==O_RDONLY){
printf("example_64 access mode: read only");
}else if(access_mode == O_WRONLY){
printf("example_64 access mode: write only");
}
if(ret&O_APPEND){
printf(",append");
}
if(ret & O_SYNC){
printf(",sync");
}
printf("\n");
return 0;
}


ret=fcntl(fd,F_SETFL,O_APPEND) shell man fcntl下查看函数: Set the file status flags to the value specified by arg. File access mode (O_RDONLY, O_WRONLY, O_RDWR) and file creation flags (i.e., O_CREAT, O_EXCL, O_NOCTTY, O_TRUNC) in
arg are ignored.On Linux this command can change only the O_APPEND, O_ASYNC O_DIRECT, O_NOATIME, and O_NONBLOCK flags. It is not possible to change the O_DSYNC and O_SYNC flags; see BUGS, below.

设置被参数arg指定的文件状态标志值。在liux下这个命令只可以改变O_APPEND, O_ASYNC O_DIRECT, O_NOATIME, O_NONBLOCK、标志,其它的标志不可以改变

ret=fcntl(fd,FGETFL,0) Get the file access mode and  the  file  status  flags;  arg  is gnored.返回值当输入参数为F_GETFL  Value of
 file status flags.返回值为文件状态标志。
access_mode=ret&O_ACCMODE;O_ACCMODE的值为三,这句是为了获得ret后两位的值,然后判断文件的打开方式
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: