把link当作lock的一个小例子
- main()
- {
- char * src = "1.txt";
- char * lockname = "1.txt.lck";
- lockfile(src, lockname);
- fp = fopen(src, "a");
- sleep(10); //at this point, it can run another instance, another instance will be pending on the "lockfile" function above.
- //write some data
- fclose(fp);
-
- unlockfile(lockname);
- }
- lockfile(char *f, char *l)
- {
- int tries = 0;
- while( tries < TOOLONG ){
- if ( link(f, l) == 0 ) /* worked? all done */
- return 0;
- if ( errno != EEXIST ){ /* other error: get out */
- perror(l);
- return 3 ;
- }
- tries++; /* count tries */
- sleep(1); /* and wait a bit */
- }
- fprintf(stderr, "Cannot set lock\n");
- return 2;
- }
- unlockfile(char *l)
- {
- int rv = 0 ;
- if ( unlink(l) == -1 ){
- perror("Cannot unlock file");
- rv = 5;
- }
- return rv;
- }