1 /*
2 * Copyright (c) 2021 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 #include <signal.h>
16 #include <sys/wait.h>
17
18 #include "control_fd.h"
19 #include "init.h"
20 #include "init_adapter.h"
21 #include "init_log.h"
22 #include "init_param.h"
23 #include "init_context.h"
24 #include "init_service_manager.h"
25 #include "loop_event.h"
26 #include "crash_handler.h"
27
28 static SignalHandle g_sigHandle = NULL;
29
HandleSigChild(const struct signalfd_siginfo * siginfo)30 static pid_t HandleSigChild(const struct signalfd_siginfo *siginfo)
31 {
32 int procStat = 0;
33 pid_t sigPID = waitpid(-1, &procStat, WNOHANG);
34 if (sigPID <= 0) {
35 return sigPID;
36 }
37 Service* service = GetServiceByPid(sigPID);
38 const char *serviceName = (service == NULL) ? "Unknown" : service->name;
39
40 // check child process exit status
41 if (WIFSIGNALED(procStat)) {
42 INIT_LOGW("Child process %s(pid %d) exit with signal : %d", serviceName, sigPID, WTERMSIG(procStat));
43 } else if (WIFEXITED(procStat)) {
44 INIT_LOGW("Child process %s(pid %d) exit with code : %d", serviceName, sigPID, WEXITSTATUS(procStat));
45 if (service != NULL) {
46 service->lastErrno = WEXITSTATUS(procStat);
47 }
48 }
49 CmdServiceProcessDelClient(sigPID);
50 StopSubInit(sigPID);
51 INIT_LOGW("Service warning %s, SIGCHLD received, pid:%d uid:%d status:%d.",
52 serviceName, sigPID, siginfo->ssi_uid, procStat);
53 CheckWaitPid(sigPID);
54 ServiceReap(service);
55 return sigPID;
56 }
57
ProcessSignal(const struct signalfd_siginfo * siginfo)58 INIT_STATIC void ProcessSignal(const struct signalfd_siginfo *siginfo)
59 {
60 switch (siginfo->ssi_signo) {
61 case SIGCHLD: {
62 while (HandleSigChild(siginfo) > 0) {
63 ;
64 }
65 break;
66 }
67 case SIGTERM: {
68 INIT_LOGI("SigHandler, SIGTERM received.");
69 SystemWriteParam("startup.device.ctl", "stop");
70 // exec reboot use toybox reboot cmd
71 ExecReboot("reboot");
72 break;
73 }
74 default:
75 INIT_LOGI("SigHandler, unsupported signal %d.", siginfo->ssi_signo);
76 break;
77 }
78 }
79
SignalInit(void)80 void SignalInit(void)
81 {
82 if (LE_CreateSignalTask(LE_GetDefaultLoop(), &g_sigHandle, ProcessSignal) == 0) {
83 if (LE_AddSignal(LE_GetDefaultLoop(), g_sigHandle, SIGCHLD) != 0) {
84 INIT_LOGW("start SIGCHLD handler failed");
85 }
86 if (LE_AddSignal(LE_GetDefaultLoop(), g_sigHandle, SIGTERM) != 0) {
87 INIT_LOGW("start SIGTERM handler failed");
88 }
89 }
90 InstallLocalSignalHandler();
91 }
92