【原创】UNIX上文件记录锁的测试

在UNIX上一般的文件操作不含有记录锁,如果多个进程同时修改某个文件,往往是最后保存的进程替换掉先前保存的线程。

但是这类I/O操作根本不适应数据库管理系统的多进程同时写操作,数据库操作要求多个进程能够利用记录锁的机制对文件的某一部分进行锁定。

系统调用fcntl 就提供了这种方法,以下是实验结果:

[@more@]

源代码:

#include
#include
#include
#include

int main()
{
struct flock lock;
int fd,pid;

lock.l_type=F_WRLCK;
lock.l_start=0;
lock.l_whence=SEEK_SET;
lock.l_len=0;

if((fd=open("./test.txt",O_WRONLY))<0)
{
printf("nError in open file !!n");
return 1;
}

if(fcntl(fd,F_SETLK,&lock)<0)
{
printf("nError in F_SETLK!! %dn",errno);
return 1;
}

if((pid=fork())<0)
{
printf("nError in fork!!n");
return 1;
}

if(pid==0)
{
if(fcntl(fd,F_GETLK,&lock)<0)
{
printf("nError in F_GETLK!!n");
return 1;
}
if(lock.l_type==F_UNLCK)
{
printf("nOK!");
return 0;
}
else
printf("nFrom child process:%d is locking file now!!",lock.l_pid);
return 0;
}
else if(pid>0)
{
waitpid(pid,NULL,0);
printf("nFrom father process:%d is my pid!n",getpid());
fflush(stdout);
close(fd);
return 0;
}
}

运行结果:

$ gcc ./lock.c -o ./lock
$ ./lock

From child process:19919 is locking file now!!
From father process:19919 is my pid!
$

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/7437037/viewspace-979433/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/7437037/viewspace-979433/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值