C小程序 - link的一个重要功能

1045阅读 0评论2012-10-24 niannian
分类:C/C++

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


上一篇:C小程序 - O_APPEND
下一篇:C小程序 - 获取终端的行和列