]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/async.c
tree-wide: remove Lennart's copyright lines
[thirdparty/systemd.git] / src / basic / async.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4 #include <pthread.h>
5 #include <stddef.h>
6 #include <unistd.h>
7
8 #include "async.h"
9 #include "fd-util.h"
10 #include "log.h"
11 #include "macro.h"
12 #include "process-util.h"
13 #include "signal-util.h"
14 #include "util.h"
15
16 int asynchronous_job(void* (*func)(void *p), void *arg) {
17 sigset_t ss, saved_ss;
18 pthread_attr_t a;
19 pthread_t t;
20 int r, k;
21
22 /* It kinda sucks that we have to resort to threads to implement an asynchronous close(), but well, such is
23 * life. */
24
25 r = pthread_attr_init(&a);
26 if (r > 0)
27 return -r;
28
29 r = pthread_attr_setdetachstate(&a, PTHREAD_CREATE_DETACHED);
30 if (r > 0) {
31 r = -r;
32 goto finish;
33 }
34
35 if (sigfillset(&ss) < 0) {
36 r = -errno;
37 goto finish;
38 }
39
40 /* Block all signals before forking off the thread, so that the new thread is started with all signals
41 * blocked. This way the existence of the new thread won't affect signal handling in other threads. */
42
43 r = pthread_sigmask(SIG_BLOCK, &ss, &saved_ss);
44 if (r > 0) {
45 r = -r;
46 goto finish;
47 }
48
49 r = pthread_create(&t, &a, func, arg);
50
51 k = pthread_sigmask(SIG_SETMASK, &saved_ss, NULL);
52
53 if (r > 0)
54 r = -r;
55 else if (k > 0)
56 r = -k;
57 else
58 r = 0;
59
60 finish:
61 pthread_attr_destroy(&a);
62 return r;
63 }
64
65 int asynchronous_sync(pid_t *ret_pid) {
66 int r;
67
68 /* This forks off an invocation of fork() as a child process, in order to initiate synchronization to
69 * disk. Note that we implement this as helper process rather than thread as we don't want the sync() to hang our
70 * original process ever, and a thread would do that as the process can't exit with threads hanging in blocking
71 * syscalls. */
72
73 r = safe_fork("(sd-sync)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS, ret_pid);
74 if (r < 0)
75 return r;
76 if (r == 0) {
77 /* Child process */
78 (void) sync();
79 _exit(EXIT_SUCCESS);
80 }
81
82 return 0;
83 }
84
85 static void *close_thread(void *p) {
86 (void) pthread_setname_np(pthread_self(), "close");
87
88 assert_se(close_nointr(PTR_TO_FD(p)) != -EBADF);
89 return NULL;
90 }
91
92 int asynchronous_close(int fd) {
93 int r;
94
95 /* This is supposed to behave similar to safe_close(), but
96 * actually invoke close() asynchronously, so that it will
97 * never block. Ideally the kernel would have an API for this,
98 * but it doesn't, so we work around it, and hide this as a
99 * far away as we can. */
100
101 if (fd >= 0) {
102 PROTECT_ERRNO;
103
104 r = asynchronous_job(close_thread, FD_TO_PTR(fd));
105 if (r < 0)
106 assert_se(close_nointr(fd) != -EBADF);
107 }
108
109 return -1;
110 }