commit b9e0c6e

default  ·  2024-12-16 18:47:27 +0000 UTC
parent 1aab3c5
Added pidfile locking.
1 files changed,  +20, -11
+20, -11
 1@@ -778,6 +778,26 @@ void httpd(void)
 2     xs *shm_name = NULL;
 3     sem_t anon_job_sem;
 4     xs *pidfile = xs_fmt("%s/server.pid", srv_basedir);
 5+    int pidfd;
 6+
 7+    {
 8+        /* do some pidfile locking acrobatics */
 9+        if ((pidfd = open(pidfile, O_RDWR | O_CREAT, 0660)) == -1) {
10+            srv_log(xs_fmt("Cannot create pidfile %s -- cannot continue", pidfile));
11+            return;
12+        }
13+
14+        if (lockf(pidfd, F_TLOCK, 1) == -1) {
15+            srv_log(xs_fmt("Cannot lock pidfile %s -- server already running?", pidfile));
16+            close(pidfd);
17+            return;
18+        }
19+
20+        ftruncate(pidfd, 0);
21+
22+        xs *s = xs_fmt("%d\n", (int)getpid());
23+        write(pidfd, s, strlen(s));
24+    }
25 
26     address = xs_dict_get(srv_config, "address");
27 
28@@ -813,17 +833,6 @@ void httpd(void)
29     srv_log(xs_fmt("httpd%s start %s %s", p_state->use_fcgi ? " (FastCGI)" : "",
30                     full_address, USER_AGENT));
31 
32-    {
33-        FILE *f;
34-
35-        if ((f = fopen(pidfile, "w")) != NULL) {
36-            fprintf(f, "%d\n", getpid());
37-            fclose(f);
38-        }
39-        else
40-            srv_log(xs_fmt("Cannot create %s: %s", pidfile, strerror(errno)));
41-    }
42-
43     /* show the number of usable file descriptors */
44     struct rlimit r;
45     getrlimit(RLIMIT_NOFILE, &r);