日期:2014-05-16 浏览次数:20902 次
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <sys/file.h>
int main()
{
//int clock = 0;
int num = 0;
int n = 0;
int i;
char buf[20];
int file = open("locktest.txt",O_RDWR);
if(file == -1)
{
fprintf(stderr,"locktest.txt open failed\n");
return;
}
fprintf(stderr,"\nlock1 file open sucess!");
struct flock flockTemp;
memset(&flockTemp,0,sizeof(flock));
fprintf(stderr,"\nflock init done!");
flockTemp.l_type = F_RDLCK;//设置共享锁
flockTemp.l_whence = SEEK_SET;//文件的第一个字节
flockTemp.l_start = 6;//文件的第二行
flockTemp.l_len = 10;
flockTemp.l_pid = -1;
fprintf(stderr,"\nlock1 = %d",getpid());
while(fcntl(file,F_SETLK,&flockTemp) == -1)
{
fprintf(stderr,"lock1获取读锁失败\n");
//检查失败的原因是不是有其它进程加了锁
if(fcntl(file,F_GETLK,&flockTemp) != -1 && (flockTemp.l_pid != -1))
{
fprintf(stderr,"进程%d获得了%d\n",flockTemp.l_pid,flockTemp.l_type);
}
else
{
fprintf(stderr,"lock1获取读锁失败\n");
return;
}
}
fprintf(stderr,"lock1获取读锁成功\n");
while(1)
{
num++;
sleep(1);
}
/*lseek(file,6,SEEK_SET);
n = read(file,buf,12);
for(i = 0; i < n; i++)
{
fprintf(stderr, "%c ",buf[i]);
}
close(file);*/
}
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
int main()
{
int clock = 0;
int n = 0;
int i;
char *str = "ggggg\nhhhhh\n";
//memset(buf,'1',20);
sleep(10);
int file = open("locktest.txt",O_RDWR);
if(file == -1)
{
fprintf(stderr,"locktest.txt open failed\n");
return;
}
struct flock flockTemp;
memset(&flockTemp,0,sizeof(flockTemp));
flockTemp.l_type = F_WRLCK;
flockTemp.l_whence = SEEK_SET;//文件的第一个字节
flockTemp.l_start = 6;//文件的第二行
flockTemp.l_len = 10;
flockTemp.l_pid = -1;
fprintf(stderr,"\nlock2 = %d",getpid());
while(fcntl(file,F_SETLK,&flockTemp) == -1)
{
fprintf(stderr,"lock2获取写锁失败\n");
//检查失败的原因是不是有其它进程加了锁
if((fcntl(file,F_GETLK,&flockTemp) != -1) && (flockTemp.l_pid != -1))
{
if(flockTemp.l_type == 0)
fprintf(stderr,"进程%d获得了读锁\n",flockTemp.l_pid);
else if(flockTemp.l_type == 1)
fprintf(stderr,"进程%d获得了写锁\n",flockTemp.l_pid);
}
else
{//其它原