home *** CD-ROM | disk | FTP | other *** search
/ The Fred Fish Collection 1.5 / ffcollection-1-5-1992-11.iso / ff_disks / 400-499 / ff473.lzh / CNewsSrc / cnews_src.lzh / libcnews / lock.c < prev    next >
C/C++ Source or Header  |  1990-12-25  |  2KB  |  93 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 "fixerrno.h"
  11. #ifdef unix
  12. # include <sys/types.h>
  13. #else
  14. # ifdef AMIGA
  15. #  include <exec/types.h>
  16. #  include <dos/dos.h>
  17. # endif /* AMIGA */
  18. #endif /* unix */
  19. #include "libc.h"
  20. #include "news.h"
  21. #include "config.h"
  22.  
  23. #define LOCKNAME "LOCK"
  24. #define LOCKTEMP "LOCKTMXXXXXX"
  25. #define INTERVAL 25        /* seconds to sleep on a busy lock */
  26.  
  27. static boolean debug = NO;
  28. static boolean mylock = NO;
  29.  
  30. void
  31. lockdebug(state)
  32. boolean state;
  33. {
  34.     debug = state;
  35. }
  36.  
  37. /*
  38.  * lock the news system.
  39.  * create a temporary name in $NEWSCTL for linking, store my pid in it.
  40.  * repeatedly try to link the temporary name to LOCKNAME.
  41.  */
  42. void
  43. newslock()
  44. {
  45.     register char *tempnm, *lockfile;
  46.     register FILE *tempfp;
  47.     int locktries = 0;
  48.  
  49.     tempnm = strsave(ctlfile(LOCKTEMP));
  50.     (void) mktemp(tempnm);
  51.     tempfp = fopen(tempnm, "w");
  52.     if (tempfp == NULL)
  53.         error("can't create lock temporary `%s'", tempnm);
  54.     (void) fprintf(tempfp, "%d\n", getpid());
  55.     (void) fclose(tempfp);
  56.  
  57.     lockfile = strsave(ctlfile(LOCKNAME));
  58.     while (link(tempnm, lockfile) < 0) {
  59.         if (errno != EEXIST)
  60.             error("can't link `%s' to LOCK", tempnm);
  61.         /*
  62.          * Could decide here if the lock is stale.
  63.          * If so, remove it and try again to lock.
  64.          */
  65.         if (debug && ++locktries == 1)
  66.             (void) printf("%s: sleeping on LOCK\n", progname);
  67.         sleep(INTERVAL);
  68.     }
  69.     free(lockfile);
  70.     (void) unlink(tempnm);
  71.     free(tempnm);
  72.     mylock = YES;
  73. }
  74.  
  75. void
  76. newsunlock()
  77. {
  78.     if (mylock) {
  79.         (void) unlink(ctlfile(LOCKNAME));
  80.         mylock = NO;
  81.     }
  82. }
  83.  
  84. void
  85. errunlock(fmt, s)        /* like error(3), but unlock before exit */
  86. char *fmt, *s;
  87. {
  88.     warning(fmt, s);
  89.     newsunlock();
  90.     exit(1);
  91.     /* NOTREACHED */
  92. }
  93.