2020-01-18 08:38:21 +00:00
|
|
|
/*
|
|
|
|
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
|
|
|
|
*
|
2021-04-22 08:24:48 +00:00
|
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
2020-01-18 08:38:21 +00:00
|
|
|
*/
|
|
|
|
|
2020-05-26 10:35:09 +00:00
|
|
|
#include <LibCore/ArgsParser.h>
|
2021-05-14 14:32:57 +00:00
|
|
|
#include <errno.h>
|
2019-06-07 09:49:31 +00:00
|
|
|
#include <signal.h>
|
|
|
|
#include <stdio.h>
|
2020-03-08 11:05:14 +00:00
|
|
|
#include <string.h>
|
2021-01-23 07:53:32 +00:00
|
|
|
#include <time.h>
|
2019-06-07 09:49:31 +00:00
|
|
|
#include <unistd.h>
|
2018-10-25 11:53:49 +00:00
|
|
|
|
2020-09-09 13:28:02 +00:00
|
|
|
static volatile bool g_interrupted;
|
2020-08-10 21:48:37 +00:00
|
|
|
static void handle_sigint(int)
|
2018-11-07 20:19:47 +00:00
|
|
|
{
|
2020-09-08 14:19:07 +00:00
|
|
|
g_interrupted = true;
|
2018-11-07 20:19:47 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
int main(int argc, char** argv)
|
|
|
|
{
|
2021-01-23 07:53:32 +00:00
|
|
|
double secs;
|
2020-05-26 10:35:09 +00:00
|
|
|
|
|
|
|
Core::ArgsParser args_parser;
|
|
|
|
args_parser.add_positional_argument(secs, "Number of seconds to sleep for", "num-seconds");
|
|
|
|
args_parser.parse(argc, argv);
|
|
|
|
|
2018-11-07 20:19:47 +00:00
|
|
|
struct sigaction sa;
|
|
|
|
memset(&sa, 0, sizeof(struct sigaction));
|
|
|
|
sa.sa_handler = handle_sigint;
|
|
|
|
sigaction(SIGINT, &sa, nullptr);
|
2020-05-26 10:52:42 +00:00
|
|
|
|
2020-09-08 14:19:07 +00:00
|
|
|
if (pledge("stdio sigaction", nullptr) < 0) {
|
2020-05-26 10:52:42 +00:00
|
|
|
perror("pledge");
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
2021-01-23 07:53:32 +00:00
|
|
|
double whole_seconds = static_cast<time_t>(secs);
|
|
|
|
double fraction = secs - whole_seconds;
|
|
|
|
|
|
|
|
timespec requested_sleep {
|
|
|
|
.tv_sec = static_cast<time_t>(whole_seconds),
|
|
|
|
.tv_nsec = static_cast<long>(fraction * (double)1000000000),
|
|
|
|
};
|
|
|
|
|
|
|
|
timespec remaining_sleep {};
|
|
|
|
|
2021-03-29 21:59:07 +00:00
|
|
|
sleep_again:
|
2021-01-23 07:53:32 +00:00
|
|
|
if (clock_nanosleep(CLOCK_MONOTONIC, 0, &requested_sleep, &remaining_sleep) < 0) {
|
|
|
|
if (errno != EINTR) {
|
|
|
|
perror("clock_nanosleep");
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (remaining_sleep.tv_sec || remaining_sleep.tv_nsec) {
|
2021-03-29 21:59:07 +00:00
|
|
|
if (!g_interrupted) {
|
|
|
|
// If not interrupted with SIGINT, just go back to sleep.
|
|
|
|
requested_sleep = remaining_sleep;
|
|
|
|
goto sleep_again;
|
|
|
|
}
|
2021-01-23 07:53:32 +00:00
|
|
|
outln("Sleep interrupted with {}.{} seconds remaining.", remaining_sleep.tv_sec, remaining_sleep.tv_nsec);
|
2018-11-07 20:19:47 +00:00
|
|
|
}
|
2020-09-08 14:19:07 +00:00
|
|
|
|
2020-09-10 13:40:32 +00:00
|
|
|
signal(SIGINT, SIG_DFL);
|
|
|
|
if (g_interrupted)
|
2020-09-08 14:19:07 +00:00
|
|
|
raise(SIGINT);
|
|
|
|
|
2018-10-25 11:53:49 +00:00
|
|
|
return 0;
|
|
|
|
}
|