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> 21 #include <sys/time.h> 22 23 #include <chrono> 24 #include <functional> 25 26 namespace android { 27 28 class ScopedAlarm { 29 public: ScopedAlarm(std::chrono::microseconds us,std::function<void ()> func)30 ScopedAlarm(std::chrono::microseconds us, std::function<void()> func) { 31 func_ = func; 32 struct sigaction act {}; 33 act.sa_handler = [](int) { ScopedAlarm::func_(); }; 34 sigaction(SIGALRM, &act, &old_act_); 35 36 std::chrono::seconds s = std::chrono::duration_cast<std::chrono::seconds>(us); 37 itimerval t = itimerval{}; 38 t.it_value.tv_sec = s.count(); 39 t.it_value.tv_usec = (us - s).count(); 40 setitimer(ITIMER_REAL, &t, NULL); 41 } ~ScopedAlarm()42 ~ScopedAlarm() { 43 itimerval t = itimerval{}; 44 setitimer(ITIMER_REAL, &t, NULL); 45 sigaction(SIGALRM, &old_act_, NULL); 46 } 47 48 private: 49 static std::function<void()> func_; 50 struct sigaction old_act_; 51 }; 52 53 } // namespace android 54 55 #endif 56