fcntl函数

fcntl 函数
1.fcntl 可以改变已打开文件的性质。
函数原型:


int fcntl( int fd, int cmd,.../* args */)


1. cmd = F_DUPFD :复制文件描述符,fcntl找到大于或等于第三个参数的最小可用的文件描述符,并复制
fd。返回新文件描述符。失败则返回-1。
例子:


#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#define BUF_SIZE 4096


int main( int argc, char *argv[] )
{
int fd1;
int fd2;
char buf[BUF_SIZE] = {0};


if( argc < 2 )
printf("More argument required\n");


fd1 = open( argv[1], O_RDONLY );


if( fd1 == -1 )
printf("open error\n");


fd2 = fcntl( fd1, F_DUPFD, 0 );


if( fd2 ==-1 )
printf( "fcntl error\n" );
while( read(fd2,buf,BUF_SIZE) != 0 )
write( STDOUT_FILENO, buf, BUF_SIZE );
close(fd1);
close(fd2);
return 0;
}


2. cmd = F_GETFD,FSETFD:得到文件描述符标置,设置文件描述符标置。目前只支持一个标志:FD_CLOEXEC。
这个标志用来表示当执行exec系列函数时父进程的文件描述符是否关闭。


例子:
//fcntl_exec.c
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>


int main( void )
{
pid_t pid;
int fd;
int flag;
char s[5] = {0};


fd = open( "gaoxin.txt", O_RDWR|O_TRUNC|O_CREAT ,0777);


snprintf(s,sizeof(s),"%d",fd);


flag = fcntl( fd, F_GETFD);
flag |= FD_CLOEXEC;
fcntl( fd, F_SETFD, flag);
pid = fork();
if( pid < 0 )
printf("fork error\n");
if( pid == 0 )
{
if ( execl("./read_file", "read_file",s, NULL )< 0)
perror("execl error\n");
}
return 0;
}


//read_file.c
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>


#define BUF_SIZE 4096
int main( int argc, char* argv[] )
{
int fd;
fd = atoi( argv[1] );
char buf[BUF_SIZE] = "gaoxin";
if ( write( fd, buf, strlen(buf) ) != strlen(buf) )
printf("write error\n");
return 0;
}


可以通过设置和取消设置FD_CLOEXEC,观察gaoxin.txt文件的内容,来理解这个标志。


cmd = F_GETFL,F_SETFL  取得文件状态标志,设置文件状态标志。可以用F_SETFL更改的标志包括:O_APPEND、O_ASYNC、O_DIRECT、O_NOATIME,O_NONBLOCK。


注意:在linux系统下面fcntl函数只能改变上述几个标志其余标志是不能用fcntl函数改变的。而且如果你设置那些不能改变的标志fcntl函数是不会报错的。
在<<unix环境高级编程>>里面介绍的一些标志是不能通过这个函数改变的,毕竟它不是完全介绍linux编程的书。还是要以man为准。



例子:
int clear_fl( int fd, int flags )
{
int val;


if( val = fcntl( fd, F_GETFL) == -1 )
{
perror("F_GETFL");
return -1;
}


val |= ~flags;


if( val = fcntl( fd, F_SETFL ) == -1 )
{
perror("F_SETFL");
return -1;
}
return 0;
}


int set_fl( int fd, int flags )
{
int val;


if( val = fcntl( fd, F_GETFL ) == -1 )
{
perror("F_GETFL");
return -1;
}


val |= flags;
if( fcntl( fd, F_SETFL, val ) == -1 )
{
perror("F_SETFL");
return -1;
}

return 0;
}







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值