1 /*
2 * Copyright (c) 2020-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 <errno.h>
16 #include <signal.h>
17 #include <sys/reboot.h>
18 #include <sys/wait.h>
19
20 #include "init_log.h"
21 #include "init_service_manager.h"
22
RebootSystem(void)23 static void RebootSystem(void)
24 {
25 #ifndef STARTUP_INIT_TEST
26 int ret = reboot(RB_AUTOBOOT);
27 if (ret != 0) {
28 INIT_LOGE("reboot failed! syscall ret %d, err %d.", ret, errno);
29 }
30 #endif
31 }
32
ReapService(Service * service)33 void ReapService(Service *service)
34 {
35 if (service == NULL) {
36 return;
37 }
38 if (service->attribute & SERVICE_ATTR_IMPORTANT) {
39 // important process exit, need to reboot system
40 service->pid = -1;
41 StopAllServices(0, NULL, 0, NULL);
42 RebootSystem();
43 }
44 ServiceReap(service);
45 }
46
SigHandler(int sig)47 static void SigHandler(int sig)
48 {
49 switch (sig) {
50 case SIGCHLD: {
51 pid_t sigPID;
52 int procStat = 0;
53 while (1) {
54 sigPID = waitpid(-1, &procStat, WNOHANG);
55 if (sigPID <= 0) {
56 break;
57 }
58 CheckWaitPid(sigPID);
59 ReapService(GetServiceByPid(sigPID));
60 }
61 break;
62 }
63 case SIGTERM: {
64 StopAllServices(0, NULL, 0, NULL);
65 break;
66 }
67 default:
68 break;
69 }
70 }
71
SignalInit(void)72 void SignalInit(void)
73 {
74 struct sigaction act;
75 act.sa_handler = SigHandler;
76 act.sa_flags = SA_RESTART;
77 (void)sigfillset(&act.sa_mask);
78
79 sigaction(SIGCHLD, &act, NULL);
80 sigaction(SIGTERM, &act, NULL);
81 }