Linux文件编程常用函数详解——fcntl()函数

fcntl()函数:

#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
int fcntl(int filedes, int cmd,.../* int arg * / ) ;
返回:若成功则依赖于cmd(见下),若出错为- 1

常见用法:

1.复制一个文件描述符;
2.获取或者设置文件状态标志;
3.获得、设置文件记录锁;

struct flock 结构体定义:

struct flock {
	short l_type;  /* 记录锁类型,F_RDLCK,F_WRLCK或F_UNLCK */
	off_t l_start;  /* 起始位置偏移量,单位字节,是相对于l_whence而言 */
	short l_whence; /* SEEK_SET,SEEK_CUR,或SEEK_END */
	off_t l_len; /* 长度,单位字节,值为0时表示一直到文件尾 */
	pid_t l_pid; /* 使用F_GETLK时返回此值 */
}

获得/设置记录锁(cmd = F_GETLK , F_SETLK或F_SETLKW)

F_GETLK是获得上锁的状态,F_SETLK是非阻塞上锁,F_SETLKW是阻塞上锁。

实例代码

#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include <errno.h>
#include <string.h>

int main(){
	/*fcntl函数可以复制文件符
	int fd1, opt, fd2;
	opt = 1;

	fd1 = open("a.txt", O_WRONLY);
	fd2 = fcntl(fd1,  F_DUPFD, opt); // fd2等价于fd1(复制文件符),且f2 >= opt

	write(fd1, "ccc", 3);
	write(fd2, "ddd", 3);

	close(fd1);
	close(fd2);*/



	/*用fcntl函数给打开的文件添加属性
	int fd, flag;
	char *p = "hello";
	char *q = "world";

	//打开文件
	fd = open("a.txt", O_WRONLY);
	if(fd == -1){
		perror("open");
		exit(1);
	}

	//从头开始写入,覆盖旧的内容
	if(write(fd, p, strlen(p)) == -1){
		perror("write");
		exit(1);
	}

	//用fcntl函数获取文件标志
	flag = fcntl(fd, F_GETFL, 0);
	if(flag == -1){
		perror("F_GETFL");
		exit(1);
	}

	//添加O_APPEND,追加写属性
	flag |= O_APPEND;

	//将新的状态字赋予文件
	if(fcntl(fd, F_SETFL, flag) == -1){
		perror("F_SETFL");
		exit(1);
	}

	//从文件末尾写入,不会覆盖旧的内容
	if(write(fd, q, strlen(q)) == -1){
		perror("write again");
		exit(1);
	}

	close(fd);
	*/



	int fd;
	fd = open("a.txt", O_RDWR);
	struct flock lck;
	lck.l_type = F_WRLCK;//设置写锁
	lck.l_start = 0;//起始位置偏移量,相对于whence而言
	lck.l_whence = SEEK_SET;//从头开始偏移
	lck.l_len = 0;//值为0时表示一直到文件尾都被锁住

	printf("start wrlock.....\n");
	fcntl(fd, F_SETLKW, &lck);//F_SETLKW是表示尝试上锁会阻塞
	printf("wrlock successfully\n");
	getchar();
	lck.l_type = F_UNLCK;//解锁
	fcntl(fd, F_SETLKW, &lck);
	printf("w unlock\n");
	close(fd); 
} 
//O_ACCMODE是宏定义的0x11,用来获取读写权限
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

正在起飞的蜗牛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值