1.实验目的
通过编写文件读写及上锁的程序,进一步熟悉Linux中文件I/O相关的应用开发,并且熟练掌握open()、read()、write()、fcntl()等函数的使用。
2.实验内容:
该实验要求首先打开一个文件,然后将该文件上写入锁,并写入hello字符串。接着在解锁后再将该文件上读取锁,并读取刚才写入的内容。最后模拟多进程,同时读写一个文件时的情况。
需要代码:
1.写入锁:
#include<stdio.h>
#include <unistd.h>
#include <sys/file.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include "lock.c"
#include<fcntl.h>
#include<string.h>
int main(void)
{
int fd;/* 首先打开文件*/
char * str="hello";
fd = open("hello", O_CREAT|O_WRONLY, 0644);if(fd < 0)
{
printf("打开文件错误!\n");
exit(1);
}
lock_set(fd, F_WRLCK); /* 写入锁*/
write(fd,str,strlen(str));
getchar(); /*按回车键继续*/
lock_set(fd, F_UNLCK); /* 给文件解锁*/
getchar();
close(fd);
exit(0);
return 0;
}
2.读取锁:
#include <unistd.h>
#include <sys/file.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lock.c"
int main(void)
{
int fd,size;fd = open("hello",O_RDWR | O_CREAT, 0644);if(fd < 0)
{
printf("打开文件错误!\n");
exit(1);
}
lock_set(fd, F_RDLCK); /* 上读取锁*/
char strBuf[200];
size=read(fd,strBuf,sizeof(strBuf));
if(size==-1){
perror("read");
}
printf("%s\n",strBuf);
getchar();
lock_set(fd, F_UNLCK); /* 解锁*/
getchar();
close(fd);
exit(0);
return 0;
}
效果截图:
1.同时写的情况:
2.同时读的情况:
注意:lock.c文件需要自己创建,大致内容如下:
int lock_set(int fd,int type)
{
struct flock old_lock,lock;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
lock.l_type = type;
lock.l_pid = -1;
fcntl(fd,F_GETLK,&lock);
if(lock.l_type != F_UNLCK)
{
if (lock.l_type == F_RDLCK)
{
printf("",lock.l_pid);
}
else if (lock.l_type == F_WRLCK)
{
printf("",lock.l_pid);
}
}
lock.l_type = type;
if ((fcntl(fd,F_SETLKW,&lock)) < 0)
{
printf("",lock.l_type);
return 1;
}
switch (lock.l_type)
{
case F_RDLCK:
{
printf("",getpid());
}
break;
case F_WRLCK:
{
printf("",getpid());
}
break;
case F_UNLCK:
{
printf("",getpid());
return 1;
}
break;
default:
break;
}
return 0;
}