]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/async.c
tree-wide: remove Emacs lines from all files
[thirdparty/systemd.git] / src / basic / async.c
1 /***
2 This file is part of systemd.
3
4 Copyright 2013 Lennart Poettering
5
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
10
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
18 ***/
19
20 #include <errno.h>
21 #include <pthread.h>
22 #include <stddef.h>
23 #include <unistd.h>
24
25 #include "async.h"
26 #include "fd-util.h"
27 #include "log.h"
28 #include "macro.h"
29 #include "util.h"
30
31 int asynchronous_job(void* (*func)(void *p), void *arg) {
32 pthread_attr_t a;
33 pthread_t t;
34 int r;
35
36 /* It kinda sucks that we have to resort to threads to
37 * implement an asynchronous sync(), but well, such is
38 * life.
39 *
40 * Note that issuing this command right before exiting a
41 * process will cause the process to wait for the sync() to
42 * complete. This function hence is nicely asynchronous really
43 * only in long running processes. */
44
45 r = pthread_attr_init(&a);
46 if (r > 0)
47 return -r;
48
49 r = pthread_attr_setdetachstate(&a, PTHREAD_CREATE_DETACHED);
50 if (r > 0)
51 goto finish;
52
53 r = pthread_create(&t, &a, func, arg);
54
55 finish:
56 pthread_attr_destroy(&a);
57 return -r;
58 }
59
60 static void *sync_thread(void *p) {
61 sync();
62 return NULL;
63 }
64
65 int asynchronous_sync(void) {
66 log_debug("Spawning new thread for sync");
67
68 return asynchronous_job(sync_thread, NULL);
69 }
70
71 static void *close_thread(void *p) {
72 assert_se(close_nointr(PTR_TO_FD(p)) != -EBADF);
73 return NULL;
74 }
75
76 int asynchronous_close(int fd) {
77 int r;
78
79 /* This is supposed to behave similar to safe_close(), but
80 * actually invoke close() asynchronously, so that it will
81 * never block. Ideally the kernel would have an API for this,
82 * but it doesn't, so we work around it, and hide this as a
83 * far away as we can. */
84
85 if (fd >= 0) {
86 PROTECT_ERRNO;
87
88 r = asynchronous_job(close_thread, FD_TO_PTR(fd));
89 if (r < 0)
90 assert_se(close_nointr(fd) != -EBADF);
91 }
92
93 return -1;
94 }