home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / gnu / fax-3.2.1 / cmd / faxspooler / seq.c < prev    next >
Encoding:
C/C++ Source or Header  |  1992-07-31  |  2.0 KB  |  107 lines

  1. /*
  2.   This file is part of the NetFax system.
  3.  
  4.   (c) Copyright 1989 by David M. Siegel. 
  5.       All rights reserved.
  6.  
  7.     This program is free software; you can redistribute it and/or modify
  8.     it under the terms of the GNU General Public License as published by
  9.     the Free Software Foundation.
  10.  
  11.     This program is distributed in the hope that it will be useful, 
  12.     but WITHOUT ANY WARRANTY; without even the implied warranty of 
  13.     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14.     GNU General Public License for more details.
  15.  
  16.     You should have received a copy of the GNU General Public License
  17.     along with this program; if not, write to the Free Software
  18.     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  19. */
  20.  
  21. #include <stdio.h>
  22. #include <errno.h>
  23. #include <fcntl.h>
  24. #include <sys/param.h>
  25.  
  26. #include "seq.h"
  27.  
  28. static int seq_lock(file)
  29.      char *file;
  30. {
  31.     char lock[MAXPATHLEN];
  32.     int lock_fd;
  33.  
  34.     sprintf(lock, "%s.lock", file);
  35.     while ((lock_fd = open(lock, O_CREAT|O_EXCL, 0666)) < 0) {
  36.     if (errno != EEXIST)
  37.       return (-1);
  38.     sleep(1);
  39.     }
  40.     close(lock_fd);
  41.  
  42.     return (0);
  43. }
  44.  
  45. static int seq_unlock(file)
  46.      char *file;
  47. {
  48.     char lock[MAXPATHLEN];
  49.  
  50.     sprintf(lock, "%s.lock", file);
  51.     unlink(lock);
  52.     
  53.     return (0);
  54. }
  55.  
  56. static int seq_write(file, numb)
  57.      char *file;
  58.      int numb;
  59. {
  60.     FILE *fp;
  61.  
  62.     if ((fp = fopen(file, "w+")) == NULL)
  63.       return (-1);
  64.  
  65.     fprintf(fp, "%d\n", numb);
  66.  
  67.     fclose(fp);
  68.  
  69.     return (numb);
  70. }
  71.  
  72. int seq_next(file)
  73.      char *file;
  74. {
  75.     FILE *fp;
  76.     int numb;
  77.  
  78.     if (seq_lock(file) < 0)
  79.       return (-1);
  80.  
  81.     if ((fp = fopen(file, "r")) == NULL) {
  82.     if (seq_write(file, 2) < 0) {
  83.         seq_unlock(file);
  84.         return (-1);
  85.     }
  86.     seq_unlock(file);
  87.     return (1);
  88.     }
  89.  
  90.     if (fscanf(fp, "%d", &numb) != 1) {
  91.     fclose(fp);
  92.     seq_unlock(file);
  93.     return (-1);
  94.     }
  95.  
  96.     fclose(fp);
  97.  
  98.     if (seq_write(file, numb+1) < 0) {
  99.     seq_unlock(file);
  100.     return (-1);
  101.     }
  102.  
  103.     seq_unlock(file);
  104.  
  105.     return (numb);
  106. }
  107.