alarm.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <Kernel/Process.h>
  7. #include <Kernel/Time/TimeManagement.h>
  8. namespace Kernel {
  9. KResultOr<FlatPtr> Process::sys$alarm(unsigned seconds)
  10. {
  11. VERIFY_PROCESS_BIG_LOCK_ACQUIRED(this);
  12. REQUIRE_PROMISE(stdio);
  13. unsigned previous_alarm_remaining = 0;
  14. if (m_alarm_timer) {
  15. bool was_in_use = false;
  16. if (TimerQueue::the().cancel_timer(*m_alarm_timer, &was_in_use)) {
  17. // The timer hasn't fired. Round up the remaining time (if any)
  18. Time remaining = m_alarm_timer->remaining() + Time::from_nanoseconds(999'999'999);
  19. previous_alarm_remaining = remaining.to_truncated_seconds();
  20. }
  21. // We had an existing alarm, must return a non-zero value here!
  22. if (was_in_use && previous_alarm_remaining == 0)
  23. previous_alarm_remaining = 1;
  24. }
  25. if (seconds > 0) {
  26. auto deadline = TimeManagement::the().current_time(CLOCK_REALTIME_COARSE);
  27. deadline = deadline + Time::from_seconds(seconds);
  28. if (!m_alarm_timer) {
  29. m_alarm_timer = adopt_ref_if_nonnull(new (nothrow) Timer());
  30. if (!m_alarm_timer)
  31. return ENOMEM;
  32. }
  33. auto timer_was_added = TimerQueue::the().add_timer_without_id(*m_alarm_timer, CLOCK_REALTIME_COARSE, deadline, [this]() {
  34. [[maybe_unused]] auto rc = send_signal(SIGALRM, nullptr);
  35. });
  36. if (!timer_was_added)
  37. return ENOMEM;
  38. }
  39. return previous_alarm_remaining;
  40. }
  41. }