Colin Cross | 7add50d | 2016-01-14 15:35:40 -0800 | [diff] [blame] | 1 | /* |
| 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 Cross | b8e20f5 | 2016-03-02 17:52:56 -0800 | [diff] [blame] | 21 | #include <sys/time.h> |
Colin Cross | 7add50d | 2016-01-14 15:35:40 -0800 | [diff] [blame] | 22 | |
| 23 | #include <chrono> |
| 24 | #include <functional> |
| 25 | |
Colin Cross | a9939e9 | 2017-06-21 13:13:00 -0700 | [diff] [blame] | 26 | namespace android { |
| 27 | |
Colin Cross | 7add50d | 2016-01-14 15:35:40 -0800 | [diff] [blame] | 28 | class ScopedAlarm { |
| 29 | public: |
| 30 | ScopedAlarm(std::chrono::microseconds us, std::function<void()> func) { |
| 31 | func_ = func; |
Colin Cross | a83881e | 2017-06-22 10:50:05 -0700 | [diff] [blame] | 32 | struct sigaction oldact {}; |
| 33 | struct sigaction act {}; |
| 34 | act.sa_handler = [](int) { ScopedAlarm::func_(); }; |
Colin Cross | 7add50d | 2016-01-14 15:35:40 -0800 | [diff] [blame] | 35 | sigaction(SIGALRM, &act, &oldact); |
| 36 | |
| 37 | std::chrono::seconds s = std::chrono::duration_cast<std::chrono::seconds>(us); |
| 38 | itimerval t = itimerval{}; |
| 39 | t.it_value.tv_sec = s.count(); |
| 40 | t.it_value.tv_usec = (us - s).count(); |
| 41 | setitimer(ITIMER_REAL, &t, NULL); |
| 42 | } |
| 43 | ~ScopedAlarm() { |
| 44 | itimerval t = itimerval{}; |
| 45 | setitimer(ITIMER_REAL, &t, NULL); |
Colin Cross | a83881e | 2017-06-22 10:50:05 -0700 | [diff] [blame] | 46 | struct sigaction act {}; |
Colin Cross | 7add50d | 2016-01-14 15:35:40 -0800 | [diff] [blame] | 47 | act.sa_handler = SIG_DFL; |
| 48 | sigaction(SIGALRM, &act, NULL); |
| 49 | } |
Colin Cross | a83881e | 2017-06-22 10:50:05 -0700 | [diff] [blame] | 50 | |
Colin Cross | 7add50d | 2016-01-14 15:35:40 -0800 | [diff] [blame] | 51 | private: |
| 52 | static std::function<void()> func_; |
| 53 | }; |
Colin Cross | a9939e9 | 2017-06-21 13:13:00 -0700 | [diff] [blame] | 54 | |
| 55 | } // namespace android |
| 56 | |
Colin Cross | 7add50d | 2016-01-14 15:35:40 -0800 | [diff] [blame] | 57 | #endif |