]> arthur.barton.de Git - netatalk.git/blob - libatalk/util/server_lock.c
90864efa138da5677e6099c4f71937c52a547d93
[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 <sys/time.h>
25
26 #include <atalk/compat.h>
27 #include <atalk/util.h>
28
29 #ifdef ATACC
30 #define fork aTaC_fork
31 #endif
32 static struct itimerval itimer;
33
34 /* this creates an open lock file which hangs around until the program
35  * dies. it returns the pid. due to problems w/ solaris, this has
36  * been changed to do the kill() thing. */
37 pid_t server_lock(char *program, char *pidfile, int debug)
38 {
39   char buf[10];
40   FILE *pf;
41   pid_t pid;
42   int mask;
43   
44   mask = umask(022);
45   /* check for pid. this can get fooled by stale pid's. */
46   if ((pf = fopen(pidfile, "r"))) {
47     if (fgets(buf, sizeof(buf), pf) && !kill(pid = atol(buf), 0)) {
48       fprintf( stderr, "%s is already running (pid = %d), or the lock file is stale.\n",
49                program, pid);      
50       fclose(pf);
51       return -1;
52     }
53     fclose(pf);
54   }
55
56   if ((pf = fopen(pidfile, "w")) == NULL) {
57     fprintf(stderr, "%s: can't open lock file, \"%s\"\n", program,
58             pidfile);
59     return -1;
60   }
61   umask(mask);
62
63   /*
64    * Disassociate from controlling tty.
65    */
66   if ( !debug ) {
67     int         i;
68
69     getitimer(ITIMER_PROF, &itimer);
70     switch (pid = fork()) {
71     case 0 :
72       setitimer(ITIMER_PROF, &itimer, NULL);
73       fclose(stdin);
74       fclose(stdout);
75       fclose(stderr);
76       i = open( "/dev/null", O_RDWR );
77       i = open( "/dev/null", O_RDWR );
78       i = open( "/dev/null", O_RDWR );
79
80 #ifdef TIOCNOTTY
81       if (( i = open( "/dev/tty", O_RDWR )) >= 0 ) {
82         (void)ioctl( i, TIOCNOTTY, 0 );
83         setpgid( 0, getpid());
84         (void) close(i);
85       }
86 #else
87       setpgid( 0, getpid());
88 #endif
89       break;
90     case -1 :  /* error */
91       perror( "fork" );
92     default :  /* server */
93       fclose(pf);
94       return pid;
95     }
96   } 
97
98   fprintf(pf, "%d\n", getpid());
99   fclose(pf);
100   return 0;
101 }
102