5.23 文件锁

这篇博客通过三个示例程序展示了在C语言中如何使用flock、fcntl和lockf函数进行文件锁定和同步操作。flock_demo.c演示了基本的文件加锁和解锁过程;fcntl.c展示了使用fcntl的F_SETLKW设置写锁;lockf.c则演示了lockf函数的加锁和解锁操作。这些示例对于理解文件锁在多进程环境中的应用至关重要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、实验代码
flock_demo.c

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

int main (void)
{
	int fd, i;
	char filename[] = "data.log";
	extern int errno;
	fd = open (filename, O_WRONLY | O_CREAT, 0666);
	if (fd != -1)
	{
		printf ("open file %s success \n", filename);
		printf ("pls input a num to lock the file.\n");
		scanf ("%d", &i);
        printf ("try to lock the file...\n");
		if (flock (fd, LOCK_EX) == 0)
			printf ("lock file success\n");
		else
			printf ("lock file failed\n");
        write (fd, "hello", 5);
		printf ("input a num to Unlock the file.\n");
		scanf ("%d", &i);
		if (flock (fd, LOCK_UN) == 0)
			printf ("file unlock success\n");
		else
			printf ("file unlock failed\n");

        while (1);
	}
	else
	{
		perror ("open");
		exit (EXIT_FAILURE);
	}
	return 0;
}

执行结果:
在这里插入图片描述
fcntl.c

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


int main (int argc, char *argv[])
{
	if (argc > 1)
	{
		int fd = open (argv[1], O_WRONLY | O_CREAT, 0666);
		if (fd == -1)
		{
			perror ("open");
			exit (-1);
		}
		static struct flock lock;
		lock.l_type = F_WRLCK;
		lock.l_start = 0;
		lock.l_whence = SEEK_SET;
		lock.l_len = 0;
		lock.l_pid = getpid();

        printf ("trying lock %s ...\n", argv[1]);
		int ret = fcntl (fd, F_SETLKW, &lock);
		if (ret == 0)
		{
		    printf ("lock %s succeed\n", argv[1]);
            while (1);
		}
	}
	return 0;
}

执行结果:
在这里插入图片描述

lockf.c

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/file.h>
int main (int argc, char *argv[])
{
	int fd, ret;
	int pid;
	fd = open ("tmp.txt", O_RDWR | O_CREAT, 0666);
	ret = flock (fd, LOCK_EX);
	printf ("flock return ret:%d\n", ret);
	ret = lockf (fd, F_LOCK, 0);
	printf ("lockf return ret:%d\n", ret);
	sleep (30);
	return 0;
}

执行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值