龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 软件开发 > C/C++开发 >

文件加锁的例题示范

时间:2009-12-22 15:42来源:未知 作者:admin 点击:
分享到:
以下例子示范了如何为文件建立独享锁: #include #include #include #include #include const char *lock_file="lock.test1"; int main() { int file_desc; int tries=10; while(tries--){ file_desc=open(lock_file,O_RDWRO_CREATO_EXCL,044

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

  

  

#include

  

#include

  

#include

  

#include

  

#include

  

  

const char *lock_file="lock.test1";

  

  

int main()

  

{

  

int file_desc;

  

int tries=10;

  

  

while(tries--){

  

file_desc=open(lock_file,O_RDWRO_CREATO_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(EX99v_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次..

  

精彩图集

赞助商链接