]> arthur.barton.de Git - netatalk.git/blob - libatalk/util/server_lock.c
patch #432052 to add portability to IRIX, HP-UX and AIX (Russ Allbery)
[netatalk.git] / libatalk / util / server_lock.c
1 /*
2  * Copyright (c) 1997 Adrian Sun (asun@zoology.washington.edu)
3  * All rights reserved. See COPYRIGHT.
4  *
5  * Copyright (c) 1990,1993 Regents of The University of Michigan.
6  * All Rights Reserved.  See COPYRIGHT.
7  */
8
9 #ifdef HAVE_CONFIG_H
10 #include "config.h"
11 #endif
12
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <unistd.h>
17 #include <fcntl.h>
18 #include <termios.h>
19 #include <sys/ioctl.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <errno.h>
23
24 #include <atalk/compat.h>
25 #include <atalk/util.h>
26
27 /* this creates an open lock file which hangs around until the program
28  * dies. it returns the pid. due to problems w/ solaris, this has
29  * been changed to do the kill() thing. */
30 pid_t server_lock(char *program, char *pidfile, int debug)
31 {
32   char buf[10];
33   FILE *pf;
34   pid_t pid;
35   int mask;
36   
37   mask = umask(022);
38   /* check for pid. this can get fooled by stale pid's. */
39   if ((pf = fopen(pidfile, "r"))) {
40     if (fgets(buf, sizeof(buf), pf) && !kill(pid = atol(buf), 0)) {
41       fprintf( stderr, "%s is already running (pid = %d), or the lock file is stale.\n",
42                program, pid);      
43       fclose(pf);
44       return -1;
45     }
46     fclose(pf);
47   }
48
49   if ((pf = fopen(pidfile, "w")) == NULL) {
50     fprintf(stderr, "%s: can't open lock file, \"%s\"\n", program,
51             pidfile);
52     return -1;
53   }
54   umask(mask);
55
56   /*
57    * Disassociate from controlling tty.
58    */
59   if ( !debug ) {
60     int         i;
61
62     switch (pid = fork()) {
63     case 0 :
64       fclose(stdin);
65       fclose(stdout);
66       fclose(stderr);
67
68 #ifdef TIOCNOTTY
69       if (( i = open( "/dev/tty", O_RDWR )) >= 0 ) {
70         (void)ioctl( i, TIOCNOTTY, 0 );
71         setpgid( 0, getpid());
72         (void) close(i);
73       }
74 #else
75       setpgid( 0, getpid());
76 #endif
77       break;
78     case -1 :  /* error */
79       perror( "fork" );
80     default :  /* server */
81       fclose(pf);
82       return pid;
83     }
84   } 
85
86   fprintf(pf, "%d\n", getpid());
87   fclose(pf);
88   return 0;
89 }