comparison lib-src/update-game-score.c @ 44576:90866353c7bd

(lock_file): If the lock file is older than an hour, delete it. Reset attempts to zero if we have to break the lock.
author Colin Walters <walters@gnu.org>
date Sun, 14 Apr 2002 06:40:19 +0000
parents 7a0ad319b38f
children 44995332ed1b
comparison
equal deleted inserted replaced
44575:52bd3d1b9cb9 44576:90866353c7bd
414 414
415 int 415 int
416 lock_file(const char *filename, void **state) 416 lock_file(const char *filename, void **state)
417 { 417 {
418 int fd; 418 int fd;
419 struct stat buf;
419 int attempts = 0; 420 int attempts = 0;
420 char *lockext = ".lockfile"; 421 char *lockext = ".lockfile";
421 char *lockpath = malloc(strlen(filename) + strlen(lockext) + 60); 422 char *lockpath = malloc(strlen(filename) + strlen(lockext) + 60);
422 if (!lockpath) 423 if (!lockpath)
423 return -1; 424 return -1;
424 strcpy(lockpath, filename); 425 strcpy(lockpath, filename);
425 strcat(lockpath, lockext); 426 strcat(lockpath, lockext);
426 *state = lockpath; 427 *state = lockpath;
427 trylock: 428 trylock:
428 attempts++; 429 attempts++;
430 /* If the lock is over an hour old, delete it. */
431 if (stat(lockpath, &buf) == 0
432 && (difftime(buf.st_ctime, time(NULL) > 60*60)))
433 unlink(lockpath);
429 if ((fd = open(lockpath, O_CREAT | O_EXCL, 0600)) < 0) 434 if ((fd = open(lockpath, O_CREAT | O_EXCL, 0600)) < 0)
430 { 435 {
431 if (errno == EEXIST) 436 if (errno == EEXIST)
432 { 437 {
433 /* Break the lock; we won't corrupt the file, but we might 438 /* Break the lock; we won't corrupt the file, but we might
434 lose some scores. */ 439 lose some scores. */
435 if (attempts > MAX_ATTEMPTS) 440 if (attempts > MAX_ATTEMPTS)
436 unlink(lockpath); 441 {
442 unlink(lockpath);
443 attempts = 0;
444 }
437 sleep((rand() % 2)+1); 445 sleep((rand() % 2)+1);
438 goto trylock; 446 goto trylock;
439 } 447 }
440 else 448 else
441 return -1; 449 return -1;