1 /*
2  * Copyright (C) 2024 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 #include "common/libs/utils/signals.h"
18 
19 #include <errno.h>
20 #include <signal.h>
21 #include <string.h>
22 
23 #include <vector>
24 
25 #include <android-base/logging.h>
26 
27 namespace cuttlefish {
28 
SignalMasker(sigset_t signals)29 SignalMasker::SignalMasker(sigset_t signals) {
30   auto res = sigprocmask(SIG_SETMASK, &signals, &old_mask_);
31   auto err = errno;
32   CHECK(res == 0) << "Failed to set thread's blocked signal mask: "
33                   << strerror(err);
34 }
35 
~SignalMasker()36 SignalMasker::~SignalMasker() {
37   auto res = sigprocmask(SIG_SETMASK, &old_mask_, NULL);
38   auto err = errno;
39   CHECK(res == 0) << "Failed to reset thread's blocked signal mask: "
40                   << strerror(err);
41 }
42 
ChangeSignalHandlers(void (* handler)(int),std::vector<int> signals)43 void ChangeSignalHandlers(void (*handler)(int), std::vector<int> signals) {
44   struct sigaction act;
45   act.sa_handler = handler;
46   sigemptyset(&act.sa_mask);
47   for (auto signal: signals) {
48     sigaddset(&act.sa_mask, signal);
49   }
50   act.sa_flags = 0;
51 
52   for (auto signal : signals) {
53     sigaction(signal, &act, NULL);
54   }
55 }
56 
57 }  // namespace cuttlefish
58 
59