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