home *** CD-ROM | disk | FTP | other *** search
/ The Fred Fish Collection 1.5 / ffcollection-1-5-1992-11.iso / ff_disks / 300-399 / ff319.lzh / CNewsSrc / cnews.src.lzh / libcnews / lock.c < prev    next >
C/C++ Source or Header  |  1989-07-03  |  2KB  |  85 lines

  1. /*
  2.  * C news system locking.
  3.  * It's compatible with B 2.10.1 news, except that locks are never
  4.  * declared stale (blow 'em away in /etc/rc).
  5.  * Only permit relaynews to run on a file server to make this sane.
  6.  */
  7.  
  8. #include <stdio.h>
  9. #include <errno.h>
  10. #include <sys/types.h>
  11. #include "libc.h"
  12. #include "news.h"
  13. #include "config.h"
  14.  
  15. #define LOCKNAME "LOCK"
  16. #define LOCKTEMP "LOCKTMXXXXXX"
  17. #define INTERVAL 25        /* seconds to sleep on a busy lock */
  18.  
  19. static boolean debug = NO;
  20. static boolean mylock = NO;
  21.  
  22. void
  23. lockdebug(state)
  24. boolean state;
  25. {
  26.     debug = state;
  27. }
  28.  
  29. /*
  30.  * lock the news system.
  31.  * create a temporary name in $NEWSCTL for linking, store my pid in it.
  32.  * repeatedly try to link the temporary name to LOCKNAME.
  33.  */
  34. void
  35. newslock()
  36. {
  37.     register char *tempnm, *lockfile;
  38.     register FILE *tempfp;
  39.     int locktries = 0;
  40.  
  41.     tempnm = strsave(ctlfile(LOCKTEMP));
  42.     (void) mktemp(tempnm);
  43.     tempfp = fopen(tempnm, "w");
  44.     if (tempfp == NULL)
  45.         error("can't create lock temporary `%s'", tempnm);
  46.     (void) fprintf(tempfp, "%d\n", getpid());
  47.     (void) fclose(tempfp);
  48.  
  49.     lockfile = strsave(ctlfile(LOCKNAME));
  50.     while (link(tempnm, lockfile) < 0) {
  51.         if (errno != EEXIST)
  52.             error("can't link `%s' to LOCK", tempnm);
  53.         /*
  54.          * Could decide here if the lock is stale.
  55.          * If so, remove it and try again to lock.
  56.          */
  57.         if (debug && ++locktries == 1)
  58.             (void) printf("%s: sleeping on LOCK\n", progname);
  59.         sleep(INTERVAL);
  60.     }
  61.     free(lockfile);
  62.     (void) unlink(tempnm);
  63.     free(tempnm);
  64.     mylock = YES;
  65. }
  66.  
  67. void
  68. newsunlock()
  69. {
  70.     if (mylock) {
  71.         (void) unlink(ctlfile(LOCKNAME));
  72.         mylock = NO;
  73.     }
  74. }
  75.  
  76. void
  77. errunlock(fmt, s)        /* like error(3), but unlock before exit */
  78. char *fmt, *s;
  79. {
  80.     warning(fmt, s);
  81.     newsunlock();
  82.     exit(1);
  83.     /* NOTREACHED */
  84. }
  85.