实验 5.2.8-3 对文件的任意部分加锁
1. 用 fcntl()对文件进行锁操作。
2. 完善课件中的示例程序,给出程序运行结果及分析。
给b.txt中的前10个字节加写锁
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<string.h>
int main()
{
char arr[]="Good good study,day day up!"; //创建或打开一个文件
int fd=open("a.txt",O_RDWR|O_CREAT|O_TRUNC,0664);
if(-1==fd) {
perror("open");
exit(-1); }
printf("文件打开成功\n"); //写入文件
int res=write(fd,arr,strlen(arr));
if(-1==res) {
perror("write");
exit(-1); }
printf("文件写入成功\n"); //准备一把写锁
struct flock lock;
lock.l_type=F_WRLCK;
lock.l_whence=SEEK_SET;
lock.l_start=0;
lock.l_len=10;
lock.l_pid=0;
//为文件上锁
res=fcntl(fd,F_SETLK,&lock);
if(-1==res) {
perror("fcntl");
exit(-1);
}
printf("加锁成功,正在关闭文件...\n");
//进程占用
sleep(5);
//关闭文件,文件锁自动释放
res=close(fd);
if(-1==res) {
perror("close");
exit(-1);
}
printf("文件成功关闭\n");
return 0;
}
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
int main() {
//1.打开文件
int fd=open("b.txt",O_WRONLY);
if(-1==fd) {
perror("open");
exit(-1);
}
printf("成功打开文件\n");
//2.写入内容
int res=write(fd,"NARUKAKA",9);
if(-1==res)
{
perror("write");
exit(-1);
}
printf("成功写入数据,共写入%d字节\n",res);
//3.关闭文件 res=close(fd);
if(-1==res) {
perror("close");
exit(-1);
}
printf("成功关闭文件\n");
return 0;
}