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