| 1 | /* Time-triggered process termination. |
| 2 | Copyright (C) 2016-2023 Free Software Foundation, Inc. |
| 3 | This file is part of the GNU C Library. |
| 4 | |
| 5 | The GNU C Library is free software; you can redistribute it and/or |
| 6 | modify it under the terms of the GNU Lesser General Public |
| 7 | License as published by the Free Software Foundation; either |
| 8 | version 2.1 of the License, or (at your option) any later version. |
| 9 | |
| 10 | The GNU C Library is distributed in the hope that it will be useful, |
| 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 13 | Lesser General Public License for more details. |
| 14 | |
| 15 | You should have received a copy of the GNU Lesser General Public |
| 16 | License along with the GNU C Library; if not, see |
| 17 | <https://www.gnu.org/licenses/>. */ |
| 18 | |
| 19 | #include <support/xthread.h> |
| 20 | #include <support/xsignal.h> |
| 21 | |
| 22 | #include <stdint.h> |
| 23 | #include <stdio.h> |
| 24 | #include <stdlib.h> |
| 25 | #include <support/check.h> |
| 26 | #include <support/support.h> |
| 27 | #include <time.h> |
| 28 | #include <unistd.h> |
| 29 | |
| 30 | struct delayed_exit_request |
| 31 | { |
| 32 | void (*exitfunc) (int); |
| 33 | int seconds; |
| 34 | }; |
| 35 | |
| 36 | static void * |
| 37 | delayed_exit_thread (void *closure) |
| 38 | { |
| 39 | struct delayed_exit_request *request = closure; |
| 40 | void (*exitfunc) (int) = request->exitfunc; |
| 41 | struct timespec delay = { request->seconds, 0 }; |
| 42 | struct timespec remaining = { 0 }; |
| 43 | free (request); |
| 44 | |
| 45 | if (nanosleep (&delay, &remaining) != 0) |
| 46 | FAIL_EXIT1 ("nanosleep: %m" ); |
| 47 | /* Exit the process successfully. */ |
| 48 | exitfunc (0); |
| 49 | return NULL; |
| 50 | } |
| 51 | |
| 52 | static void |
| 53 | delayed_exit_1 (int seconds, void (*exitfunc) (int)) |
| 54 | { |
| 55 | /* Create the new thread with all signals blocked. */ |
| 56 | sigset_t all_blocked; |
| 57 | sigfillset (&all_blocked); |
| 58 | sigset_t old_set; |
| 59 | xpthread_sigmask (SIG_SETMASK, &all_blocked, &old_set); |
| 60 | struct delayed_exit_request *request = xmalloc (sizeof (*request)); |
| 61 | request->seconds = seconds; |
| 62 | request->exitfunc = exitfunc; |
| 63 | /* Create a detached thread. */ |
| 64 | pthread_t thr = xpthread_create (NULL, delayed_exit_thread, request); |
| 65 | xpthread_detach (thr); |
| 66 | /* Restore the original signal mask. */ |
| 67 | xpthread_sigmask (SIG_SETMASK, &old_set, NULL); |
| 68 | } |
| 69 | |
| 70 | void |
| 71 | delayed_exit (int seconds) |
| 72 | { |
| 73 | delayed_exit_1 (seconds, exit); |
| 74 | } |
| 75 | |
| 76 | void |
| 77 | delayed__exit (int seconds) |
| 78 | { |
| 79 | delayed_exit_1 (seconds, _exit); |
| 80 | } |
| 81 | |