1 /*
2  * Copyright (C) 2010 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 <errno.h>
18 #include <fcntl.h>
19 #include <signal.h>
20 #include <stdio.h>
21 #include <sys/socket.h>
22 #include <sys/types.h>
23 #include <sys/wait.h>
24 #include <unistd.h>
25 
26 #include <android-base/stringprintf.h>
27 #include <cutils/android_reboot.h>
28 #include <cutils/list.h>
29 #include <cutils/sockets.h>
30 
31 #include "action.h"
32 #include "init.h"
33 #include "log.h"
34 #include "service.h"
35 #include "util.h"
36 
37 static int signal_write_fd = -1;
38 static int signal_read_fd = -1;
39 
handle_signal()40 static void handle_signal() {
41     // Clear outstanding requests.
42     char buf[32];
43     read(signal_read_fd, buf, sizeof(buf));
44 
45     ServiceManager::GetInstance().ReapAnyOutstandingChildren();
46 }
47 
SIGCHLD_handler(int)48 static void SIGCHLD_handler(int) {
49     if (TEMP_FAILURE_RETRY(write(signal_write_fd, "1", 1)) == -1) {
50         ERROR("write(signal_write_fd) failed: %s\n", strerror(errno));
51     }
52 }
53 
signal_handler_init()54 void signal_handler_init() {
55     // Create a signalling mechanism for SIGCHLD.
56     int s[2];
57     if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0, s) == -1) {
58         ERROR("socketpair failed: %s\n", strerror(errno));
59         exit(1);
60     }
61 
62     signal_write_fd = s[0];
63     signal_read_fd = s[1];
64 
65     // Write to signal_write_fd if we catch SIGCHLD.
66     struct sigaction act;
67     memset(&act, 0, sizeof(act));
68     act.sa_handler = SIGCHLD_handler;
69     act.sa_flags = SA_NOCLDSTOP;
70     sigaction(SIGCHLD, &act, 0);
71 
72     ServiceManager::GetInstance().ReapAnyOutstandingChildren();
73 
74     register_epoll_handler(signal_read_fd, handle_signal);
75 }
76