Andrew Geissler | 517393d | 2023-01-13 08:55:19 -0600 | [diff] [blame^] | 1 | From 212a947e776e7a25c1f2259615f461179bcb3663 Mon Sep 17 00:00:00 2001 |
| 2 | From: Alexander Kanavin <alex@linutronix.de> |
| 3 | Date: Wed, 23 Nov 2022 21:38:38 +0100 |
| 4 | Subject: [PATCH] daemon.c: Fix race window for writing of the pid file |
| 5 | |
| 6 | The parent process should write the pid file such that the pid file |
| 7 | will can be checked immediately following exit of the fork from the |
| 8 | parent. |
| 9 | |
| 10 | This allows external monitoring applications to watch the daemon |
| 11 | without having to add sleep calls to wait for the pid file be written |
| 12 | on a busy system. |
| 13 | |
| 14 | Upstream-Status: Submitted [https://github.com/unfs3/unfs3/pull/28] |
| 15 | Signed-off-by: Jason Wessel <jason.wessel@windriver.com> |
| 16 | Signed-off-by: Alexander Kanavin <alex@linutronix.de> |
| 17 | --- |
| 18 | daemon.c | 12 +++++++++--- |
| 19 | 1 file changed, 9 insertions(+), 3 deletions(-) |
| 20 | |
| 21 | diff --git a/daemon.c b/daemon.c |
| 22 | index ff53b7a..13b06a4 100644 |
| 23 | --- a/daemon.c |
| 24 | +++ b/daemon.c |
| 25 | @@ -166,7 +166,7 @@ int get_socket_type(struct svc_req *rqstp) |
| 26 | /* |
| 27 | * write current pid to a file |
| 28 | */ |
| 29 | -static void create_pid_file(void) |
| 30 | +static void create_pid_file(int pid) |
| 31 | { |
| 32 | char buf[16]; |
| 33 | int fd, res, len; |
| 34 | @@ -188,7 +188,7 @@ static void create_pid_file(void) |
| 35 | } |
| 36 | #endif |
| 37 | |
| 38 | - sprintf(buf, "%i\n", backend_getpid()); |
| 39 | + sprintf(buf, "%i\n", pid); |
| 40 | len = strlen(buf); |
| 41 | |
| 42 | res = backend_pwrite(fd, buf, len, 0); |
| 43 | @@ -1122,6 +1122,10 @@ int main(int argc, char **argv) |
| 44 | fprintf(stderr, "could not fork into background\n"); |
| 45 | daemon_exit(0); |
| 46 | } |
| 47 | + if (pid) |
| 48 | + create_pid_file(pid); |
| 49 | + } else { |
| 50 | + create_pid_file(backend_getpid()); |
| 51 | } |
| 52 | #endif /* WIN32 */ |
| 53 | |
| 54 | @@ -1161,8 +1165,10 @@ int main(int argc, char **argv) |
| 55 | /* no umask to not screw up create modes */ |
| 56 | umask(0); |
| 57 | |
| 58 | +#ifdef WIN32 |
| 59 | /* create pid file if wanted */ |
| 60 | - create_pid_file(); |
| 61 | + create_pid_file(backend_getpid()); |
| 62 | +#endif |
| 63 | |
| 64 | /* initialize internal stuff */ |
| 65 | fh_cache_init(); |
| 66 | -- |
| 67 | 2.30.2 |
| 68 | |