blob: 53ea112068f5fc161f83ec3cd0fa369496b45266 [file] [log] [blame]
Colin Cross7add50d2016-01-14 15:35:40 -08001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef LIBMEMUNREACHABLE_SCOPED_ALARM_H_
18#define LIBMEMUNREACHABLE_SCOPED_ALARM_H_
19
20#include <signal.h>
Colin Crossb8e20f52016-03-02 17:52:56 -080021#include <sys/time.h>
Colin Cross7add50d2016-01-14 15:35:40 -080022
23#include <chrono>
24#include <functional>
25
26class ScopedAlarm {
27 public:
28 ScopedAlarm(std::chrono::microseconds us, std::function<void()> func) {
29 func_ = func;
Colin Crossa83881e2017-06-22 10:50:05 -070030 struct sigaction oldact {};
31 struct sigaction act {};
32 act.sa_handler = [](int) { ScopedAlarm::func_(); };
Colin Cross7add50d2016-01-14 15:35:40 -080033 sigaction(SIGALRM, &act, &oldact);
34
35 std::chrono::seconds s = std::chrono::duration_cast<std::chrono::seconds>(us);
36 itimerval t = itimerval{};
37 t.it_value.tv_sec = s.count();
38 t.it_value.tv_usec = (us - s).count();
39 setitimer(ITIMER_REAL, &t, NULL);
40 }
41 ~ScopedAlarm() {
42 itimerval t = itimerval{};
43 setitimer(ITIMER_REAL, &t, NULL);
Colin Crossa83881e2017-06-22 10:50:05 -070044 struct sigaction act {};
Colin Cross7add50d2016-01-14 15:35:40 -080045 act.sa_handler = SIG_DFL;
46 sigaction(SIGALRM, &act, NULL);
47 }
Colin Crossa83881e2017-06-22 10:50:05 -070048
Colin Cross7add50d2016-01-14 15:35:40 -080049 private:
50 static std::function<void()> func_;
51};
52#endif