论坛交流
首页办公自动化| 网页制作| 平面设计| 动画制作| 数据库开发| 程序设计| 全部视频教程
应用视频: Windows | Word2007 | Excel2007 | PowerPoint2007 | Dreamweaver 8 | Fireworks 8 | Flash 8 | Photoshop cs | CorelDraw 12
编程视频: C语言视频教程 | HTML | Div+Css布局 | Javascript | Access数据库 | Asp | Sql Server数据库Asp.net  | Flash AS
当前位置 > 文字教程 > C语言程序设计教程
Tag:新手,函数,指针,数据类型,对象,Turbo,入门,运算符,数组,结构,二级,,tc,游戏,试题,问答,编译,视频教程

文件加锁的例题示范

文章类别:C语言程序设计 | 发表日期:2008-9-24 14:36:54

以下例子示范了如何为文件建立独享锁:

#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<fcntl.h>
#include<errno.h>

const char *lock_file="lock.test1";

int main()
{
int file_desc;
int tries=10;

while(tries--){
file_desc=open(lock_file,O_RDWR|O_CREAT|O_EXCL,0444);
if(file_desc==-1){
printf("%d - Lock already present
",getpid());
sleep(1);
} else {
printf("%d - I have exclusive access
",getpid());
sleep(1);
(void)close(file_desc);
(void)unlink(lock_file);
sleep(1);
}
}
exit(EXIT_SUCCESS);
}

要想看到加锁的效果,得运行:./lock&./lock
我在 Linux 下运行的结果:
[1] 18396
18396 - I have exclusive access
18397 - Lock already present
18397 - I have exclusive access
18396 - Lock already present
18396 - I have exclusive access
18397 - Lock already present
18397 - I have exclusive access
18396 - Lock already present
18396 - I have exclusive access
18397 - Lock already present
18397 - I have exclusive access
18396 - Lock already present
18396 - I have exclusive access
18397 - Lock already present
18397 - I have exclusive access
18396 - Lock already present
18396 - I have exclusive access
18397 - Lock already present
18397 - I have exclusive access
18396 - Lock already present
[1]+ Done ./lock

结果解析:第一个lock运行的进程号为18396,加锁成功后输出:I have exclusive access,然后休眠1秒,此时第二个lock开始运行,并试图给文件加锁但失败输出:Lock already present,并开始休眠1秒,之后第一个loxk清醒并解锁,再休眠1秒,第二个lock运行加锁成功,如次反复运行10次..
视频教程列表
文章教程搜索
 
C语言程序设计推荐教程
C语言程序设计热门教程
看全部视频教程
购买方式/价格
购买视频教程: 咨询客服
tel:15972130058