2020-07-30 23:38:15 +02:00
|
|
|
/*
|
|
|
|
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
|
|
|
|
*
|
2021-04-22 01:24:48 -07:00
|
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
2020-07-30 23:38:15 +02:00
|
|
|
*/
|
|
|
|
|
|
|
|
#include <Kernel/Process.h>
|
|
|
|
#include <Kernel/Time/TimeManagement.h>
|
|
|
|
|
|
|
|
namespace Kernel {
|
|
|
|
|
2021-03-01 13:49:16 +01:00
|
|
|
KResultOr<unsigned> Process::sys$alarm(unsigned seconds)
|
2020-07-30 23:38:15 +02:00
|
|
|
{
|
|
|
|
REQUIRE_PROMISE(stdio);
|
|
|
|
unsigned previous_alarm_remaining = 0;
|
2021-05-20 00:41:51 +02:00
|
|
|
if (m_alarm_timer) {
|
|
|
|
if (TimerQueue::the().cancel_timer(*m_alarm_timer)) {
|
2020-12-01 15:44:52 -07:00
|
|
|
// The timer hasn't fired. Round up the remaining time (if any)
|
2021-05-20 00:41:51 +02:00
|
|
|
Time remaining = m_alarm_timer->remaining() + Time::from_nanoseconds(999'999'999);
|
2021-02-27 23:56:16 +01:00
|
|
|
previous_alarm_remaining = remaining.to_truncated_seconds();
|
2020-12-01 15:44:52 -07:00
|
|
|
}
|
|
|
|
// We had an existing alarm, must return a non-zero value here!
|
|
|
|
if (previous_alarm_remaining == 0)
|
|
|
|
previous_alarm_remaining = 1;
|
2020-07-30 23:38:15 +02:00
|
|
|
}
|
2020-12-01 15:44:52 -07:00
|
|
|
|
|
|
|
if (seconds > 0) {
|
2021-05-05 16:51:06 +00:00
|
|
|
auto deadline = TimeManagement::the().current_time(CLOCK_REALTIME_COARSE);
|
2021-02-27 23:56:16 +01:00
|
|
|
deadline = deadline + Time::from_seconds(seconds);
|
2021-05-20 00:41:51 +02:00
|
|
|
if (!m_alarm_timer) {
|
|
|
|
m_alarm_timer = adopt_ref_if_nonnull(new Timer());
|
|
|
|
if (!m_alarm_timer)
|
|
|
|
return ENOMEM;
|
|
|
|
}
|
|
|
|
auto timer_was_added = TimerQueue::the().add_timer_without_id(*m_alarm_timer, CLOCK_REALTIME_COARSE, deadline, [this]() {
|
2020-12-20 16:09:48 -07:00
|
|
|
[[maybe_unused]] auto rc = send_signal(SIGALRM, nullptr);
|
2020-12-01 15:44:52 -07:00
|
|
|
});
|
2021-05-20 00:41:51 +02:00
|
|
|
if (!timer_was_added)
|
|
|
|
return ENOMEM;
|
2020-07-30 23:38:15 +02:00
|
|
|
}
|
|
|
|
return previous_alarm_remaining;
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|