chiark / gitweb /
Make tmpdir removal asynchronous
[elogind.git] / src / core / async.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2013 Lennart Poettering
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU Lesser General Public License as published by
10   the Free Software Foundation; either version 2.1 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   Lesser General Public License for more details.
17
18   You should have received a copy of the GNU Lesser General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <pthread.h>
23 #include <unistd.h>
24
25 #include "async.h"
26 #include "log.h"
27
28 int asynchronous_job(void* (*func)(void *p), void *arg) {
29         pthread_attr_t a;
30         pthread_t t;
31         int r;
32
33         /* It kinda sucks that we have to resort to threads to
34          * implement an asynchronous sync(), but well, such is
35          * life.
36          *
37          * Note that issuing this command right before exiting a
38          * process will cause the process to wait for the sync() to
39          * complete. This function hence is nicely asynchronous really
40          * only in long running processes. */
41
42         r = pthread_attr_init(&a);
43         if (r != 0)
44                 return -r;
45
46         r = pthread_attr_setdetachstate(&a, PTHREAD_CREATE_DETACHED);
47         if (r != 0) {
48                 r = -r;
49                 goto finish;
50         }
51
52         r = pthread_create(&t, &a, func, arg);
53         if (r != 0) {
54                 r = -r;
55                 goto finish;
56         }
57
58 finish:
59         pthread_attr_destroy(&a);
60         return r;
61 }
62
63 static void *sync_thread(void *p) {
64         sync();
65         return NULL;
66 }
67
68 int asynchronous_sync(void) {
69         log_debug("Spawning new thread for sync");
70
71         return asynchronous_job(sync_thread, NULL);
72 }