home *** CD-ROM | disk | FTP | other *** search
- /*
- ** Lock 'file' using a 'file'.lck protocol.
- **
- ** This is public domain.
- ** Robert Osborne.
- **
- ** $Id: lock.c,v 1.1 1991/04/30 19:16:26 robert Exp $
- */
- #include <stdio.h>
- #include <sys/types.h>
- #include <sys/stat.h>
-
- lock_file(path, oldest, sec)
- char *path; /* file we want to 'lock' */
- unsigned int oldest; /* delete file if older than oldest */
- unsigned int sec; /* seconds we are willing to wait */
- {
- char lpath[1024];
- int locked = 0;
- struct stat buf;
- time_t age = 0;
- FILE *fp;
-
- sprintf(lpath, "%s.lck", path);
-
- while( ! locked )
- {
- if( stat(lpath, &buf) == -1 )
- {
- if( (fp = fopen(lpath, "w")) == (FILE *) 0 )
- {
- return 0;
- }
- fclose(fp);
- return 1;
- }
-
- /* get the age of file */
- if( age == 0 )
- {
- age = time((long *)0) - buf.st_mtime;
- }
-
- #ifdef TEST_LOCK
- printf("age=%ld\n", age);
- #endif
- if( age > oldest )
- {
- unlink(lpath);
- continue;
- }
-
- if( sec == 0 ) break;
- sleep(1);
- sec--;
- age++;
- }
- return locked;
- }
-
- unlock_file(path)
- char *path; /* file we want to 'unlock' */
- {
- char lpath[1024];
- struct stat buf;
-
- sprintf(lpath, "%s.lck", path);
- unlink(lpath);
- }
- #ifdef TEST_LOCK
- main(argc,argv)
- int argc;
- char *argv[];
- {
- extern char *optarg;
- extern int optind;
- int c;
- int age = 100;
- int sec = 2;
-
- while((c=getopt(argc, argv, "?Hs:a:LU")) != EOF ) {
- switch(c) {
- case 's':
- sec = atoi(optarg);
- break;
- case 'a':
- age = atoi(optarg);
- break;
- case 'L':
- if( lock_file("test", age, sec) )
- printf("lock success\n");
- else
- printf("lock failed\n");
- break;
- case 'U':
- unlock_file("test");
- break;
- default:
- fprintf(stderr, "usage: %s [ -s seconds -a age] -L | -U\n",
- argv[0]);
- }
- }
-
- }
- #endif
-