Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1727809
  • 博文数量: 782
  • 博客积分: 2455
  • 博客等级: 大尉
  • 技术积分: 4140
  • 用 户 组: 普通用户
  • 注册时间: 2011-04-06 21:37
个人简介

Linux ,c/c++, web,前端,php,js

文章分类

全部博文(782)

文章存档

2015年(8)

2014年(28)

2013年(110)

2012年(307)

2011年(329)

分类:

2012-10-25 09:08:09

The link("old","new") will fail if "new" exists and will succeed if it can create "new". Therefore, if several processes try to create a link called "new" at once, if one succeeds, the other ones will fail. In that manner, the link system can be used to pick one process out of many. The existence of that link can be used as lock.

把link当作lock的一个小例子

  1. main()
  2. {
  3.     char * src = "1.txt";
  4.     char * lockname = "1.txt.lck";

  5.     lockfile(src, lockname);

  6.     fp = fopen(src, "a");
  7.     sleep(10); //at this point, it can run another instance, another instance will be pending on the "lockfile" function above.
  8.     //write some data
  9.     fclose(fp);
  10.     
  11.     unlockfile(lockname);
  12. }

  13. lockfile(char *f, char *l)
  14. {
  15.     int    tries = 0;

  16.     while( tries < TOOLONG ){
  17.         if ( link(f, l) == 0 )        /* worked? all done    */
  18.             return 0;
  19.         if ( errno != EEXIST ){        /* other error: get out    */
  20.             perror(l);
  21.             return 3 ;
  22.         }
  23.         tries++;            /* count tries        */
  24.         sleep(1);            /* and wait a bit    */
  25.     }
  26.     fprintf(stderr, "Cannot set lock\n");
  27.     return 2;
  28. }

  29. unlockfile(char *l)
  30. {
  31.     int    rv = 0 ;

  32.     if ( unlink(l) == -1 ){
  33.         perror("Cannot unlock file");
  34.         rv = 5;
  35.     }
  36.     return rv;
  37. }


阅读(534) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~