Chinaunix首页 | 论坛 | 博客
  • 博客访问: 742705
  • 博文数量: 130
  • 博客积分: 2951
  • 博客等级: 少校
  • 技术积分: 1875
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-04 18:32
文章分类

全部博文(130)

文章存档

2013年(1)

2012年(129)

分类: C/C++

2012-10-24 15:36:37

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. }


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