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