]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/async.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2013 Lennart Poettering
7 systemd is free software; you can redistribute it and/or modify it
8 under the terms of the GNU Lesser General Public License as published by
9 the Free Software Foundation; either version 2.1 of the License, or
10 (at your option) any later version.
12 systemd is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Lesser General Public License for more details.
17 You should have received a copy of the GNU Lesser General Public License
18 along with systemd; If not, see <http://www.gnu.org/licenses/>.
30 #include "process-util.h"
31 #include "signal-util.h"
34 int asynchronous_job(void* (*func
)(void *p
), void *arg
) {
35 sigset_t ss
, saved_ss
;
40 /* It kinda sucks that we have to resort to threads to implement an asynchronous close(), but well, such is
43 r
= pthread_attr_init(&a
);
47 r
= pthread_attr_setdetachstate(&a
, PTHREAD_CREATE_DETACHED
);
53 if (sigfillset(&ss
) < 0) {
58 /* Block all signals before forking off the thread, so that the new thread is started with all signals
59 * blocked. This way the existence of the new thread won't affect signal handling in other threads. */
61 r
= pthread_sigmask(SIG_BLOCK
, &ss
, &saved_ss
);
67 r
= pthread_create(&t
, &a
, func
, arg
);
69 k
= pthread_sigmask(SIG_SETMASK
, &saved_ss
, NULL
);
79 pthread_attr_destroy(&a
);
83 int asynchronous_sync(pid_t
*ret_pid
) {
86 /* This forks off an invocation of fork() as a child process, in order to initiate synchronization to
87 * disk. Note that we implement this as helper process rather than thread as we don't want the sync() to hang our
88 * original process ever, and a thread would do that as the process can't exit with threads hanging in blocking
91 r
= safe_fork("(sd-sync)", FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
, ret_pid
);
103 static void *close_thread(void *p
) {
104 (void) pthread_setname_np(pthread_self(), "close");
106 assert_se(close_nointr(PTR_TO_FD(p
)) != -EBADF
);
110 int asynchronous_close(int fd
) {
113 /* This is supposed to behave similar to safe_close(), but
114 * actually invoke close() asynchronously, so that it will
115 * never block. Ideally the kernel would have an API for this,
116 * but it doesn't, so we work around it, and hide this as a
117 * far away as we can. */
122 r
= asynchronous_job(close_thread
, FD_TO_PTR(fd
));
124 assert_se(close_nointr(fd
) != -EBADF
);