2 * Copyright 2006-2007 Free Software Foundation, Inc.
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18 * Reap any leftover children possibly holding file descriptors.
19 * Children are identified by the stale file descriptor or PGID / SID.
20 * Both can be missed but only the stale file descriptors are important for us.
21 * PGID / SID may be set by the children on their own.
22 * If we fine a candidate we kill it will all its process tree (grandchildren).
23 * The child process is run with `2>&1' redirection (due to forkpty(3)).
24 * 2007-07-10 Jan Kratochvil <jan.kratochvil@redhat.com>
32 #include <sys/types.h>
45 #define LENGTH(x) (sizeof (x) / sizeof (*(x)))
47 static const char *progname;
49 static volatile int signal_child_hit = 0;
51 /* We use it to race-safely emulate ppoll(2) by poll(2). */
54 static void signal_child (int signo)
60 assert (pipefd[1] != -1);
61 i = close (pipefd[1]);
66 static char childptyname[LINE_MAX];
69 static int spawn (char **argv)
72 int status, amaster, i;
74 struct termios termios;
79 /* We do not use signal(2) to be sure we have SA_RESTART set. */
80 memset (&act, 0, sizeof (act));
81 act.sa_handler = signal_child;
82 i = sigemptyset (&act.sa_mask);
84 act.sa_flags = SA_RESTART;
85 i = sigaction (SIGCHLD, &act, NULL);
88 /* With TERMP passed as NULL we get "\n" -> "\r\n". */
89 termios.c_iflag = IGNBRK | IGNPAR;
91 termios.c_cflag = CS8 | CREAD | CLOCAL | HUPCL | B9600;
92 termios.c_lflag = IEXTEN | NOFLSH;
93 memset (termios.c_cc, _POSIX_VDISABLE, sizeof (termios.c_cc));
94 termios.c_cc[VTIME] = 0;
95 termios.c_cc[VMIN ] = 1;
98 /* Workaround a readline deadlock bug in _get_tty_settings(). */
99 termios.c_lflag &= ~FLUSHO;
101 child = forkpty (&amaster, childptyname, &termios, NULL);
105 perror ("forkpty(3)");
108 i = close (pipefd[0]);
110 i = close (pipefd[1]);
113 /* Do not replace STDIN as inferiors query its termios. */
115 i = close (STDIN_FILENO);
117 i = open ("/dev/null", O_RDONLY);
118 assert (i == STDIN_FILENO);
121 /* Do not setpgrp(2) in the parent process as the process-group
122 is shared for the whole sh(1) pipeline we could be a part
123 of. The process-group is set according to PID of the first
124 command in the pipeline.
125 We would rip even vi(1) in the case of:
126 ./orphanripper sh -c 'sleep 1&' | vi -
128 /* Do not setpgrp(2) as our pty would not be ours and we would
129 get `SIGSTOP' later, particularly after spawning gdb(1).
130 setsid(3) was already executed by forkpty(3) and it would fail if
132 if (getpid() != getpgrp ())
134 perror ("getpgrp(2)");
137 execvp (argv[1], argv + 1);
138 perror ("execvp(2)");
143 i = fcntl (amaster, F_SETFL, O_RDWR | O_NONBLOCK);
146 perror ("fcntl (amaster, F_SETFL, O_NONBLOCK)");
151 struct pollfd pollfd[2];
155 pollfd[0].fd = amaster;
156 pollfd[0].events = POLLIN;
157 pollfd[1].fd = pipefd[0];
158 pollfd[1].events = POLLIN;
159 i = poll (pollfd, LENGTH (pollfd), -1);
160 if (i == -1 && errno == EINTR)
162 /* Weird but SA_RESTART sometimes does not work. */
166 /* Data available? Process it first. */
167 if (pollfd[0].revents & POLLIN)
169 buf_got = read (amaster, buf, sizeof buf);
172 perror ("read (amaster)");
175 if (write (STDOUT_FILENO, buf, buf_got) != buf_got)
181 if (pollfd[0].revents & POLLHUP)
183 if ((pollfd[0].revents &= ~POLLIN) != 0)
185 fprintf (stderr, "%s: ppoll(2): revents 0x%x\n", progname,
186 (unsigned) pollfd[0].revents);
190 if (pollfd[1].revents & POLLHUP)
192 assert (pollfd[1].revents == 0);
194 /* WNOHANG still could fail. */
195 child_got = waitpid (child, &status, 0);
196 if (child != child_got)
198 fprintf (stderr, "waitpid (%d) = %d: %m\n", (int) child, (int) child_got);
201 if (!WIFEXITED (status))
203 fprintf (stderr, "waitpid (%d): !WIFEXITED (%d)\n", (int) child, status);
207 assert (signal_child_hit != 0);
208 assert (pipefd[1] == -1);
209 i = close (pipefd[0]);
212 /* Do not close the master FD as the child would have `/dev/pts/23 (deleted)'
213 entries which are not expected (and expecting ` (deleted)' would be
219 perror ("close (forkpty ()'s amaster)");
224 return WEXITSTATUS (status);
227 /* Detected commandline may look weird due to a race:
229 ./orphanripper sh -c 'sleep 1&' &
232 ./orphanripper: Killed -9 orphan PID 29612 (PGID 29611): sleep 1
233 Raced output (sh(1) child still did not update its argv[]):
235 ./orphanripper: Killed -9 orphan PID 29615 (PGID 29614): sh -c sleep 1&
236 We could delay a bit before ripping the children. */
237 static const char *read_cmdline (pid_t pid)
239 char cmdline_fname[32];
240 static char cmdline[LINE_MAX];
245 if (snprintf (cmdline_fname, sizeof cmdline_fname, "/proc/%d/cmdline",
248 fd = open (cmdline_fname, O_RDONLY);
251 /* It may have already exited - ENOENT. */
253 fprintf (stderr, "%s: open (\"%s\"): %m\n", progname, cmdline_fname);
257 got = read (fd, cmdline, sizeof (cmdline) - 1);
259 fprintf (stderr, "%s: read (\"%s\"): %m\n", progname,
262 fprintf (stderr, "%s: close (\"%s\"): %m\n", progname,
266 /* Convert '\0' argument delimiters to spaces. */
267 for (s = cmdline; s < cmdline + got; s++)
270 /* Trim the trailing spaces (typically single '\0'->' '). */
271 while (s > cmdline && isspace (s[-1]))
277 static int fd_fs_scan (pid_t pid, int (*func) (pid_t pid, const char *link))
280 struct dirent *dirent;
284 if (snprintf (dirname, sizeof dirname, "/proc/%d/fd", (int) pid) < 0)
286 perror ("snprintf(3)");
289 dir = opendir (dirname);
292 if (errno == EACCES || errno == ENOENT)
294 fprintf (stderr, "%s: opendir (\"%s\"): %m\n", progname, dirname);
297 while ((errno = 0, dirent = readdir (dir)))
299 char linkname[LINE_MAX], buf[LINE_MAX];
303 /* FIXME: POSIX portability. */
304 if ((dirent->d_type != DT_DIR && dirent->d_type != DT_LNK)
305 || (dirent->d_type == DT_DIR && strcmp (dirent->d_name, ".") != 0
306 && strcmp (dirent->d_name, "..") != 0)
307 || (dirent->d_type == DT_LNK && strspn (dirent->d_name, "0123456789")
308 != strlen (dirent->d_name)))
310 /* There is a race, D_TYPE may be uninitialized if stat(2) fails. */
311 if (dirent->d_type != DT_UNKNOWN)
312 fprintf (stderr, "Unexpected entry \"%s\" (d_type %u)"
313 " on readdir (\"%s\"): %m\n",
314 dirent->d_name, (unsigned) dirent->d_type, dirname);
317 if (dirent->d_type == DT_DIR)
319 linkname_len = snprintf (linkname, sizeof linkname, "%s/%s", dirname,
321 if (linkname_len <= 0 || linkname_len >= sizeof linkname)
323 fprintf (stderr, "Link content too long: `%s' / `%s'\n",
324 dirent->d_name, dirent->d_name);
327 buf_len = readlink (linkname, buf, sizeof buf - 1);
328 if (buf_len <= 0 || buf_len >= sizeof buf - 1)
330 if (errno != ENOENT && errno != EACCES)
331 fprintf (stderr, "Error reading link \"%s\": %m\n",
336 rc = (*func) (pid, buf);
345 fprintf (stderr, "%s: readdir (\"%s\"): %m\n", progname, dirname);
348 if (closedir (dir) != 0)
350 fprintf (stderr, "%s: closedir (\"%s\"): %m\n", progname, dirname);
356 static void pid_fs_scan (void (*func) (pid_t pid, void *data), void *data)
359 struct dirent *dirent;
361 dir = opendir ("/proc");
364 perror ("opendir (\"/proc\")");
367 while ((errno = 0, dirent = readdir (dir)))
369 /* FIXME: POSIX portability. */
370 if (dirent->d_type != DT_DIR
371 || strspn (dirent->d_name, "0123456789") != strlen (dirent->d_name))
373 (*func) (atoi (dirent->d_name), data);
377 perror ("readdir (\"/proc\")");
380 if (closedir (dir) != 0)
382 perror ("closedir (\"/proc\")");
387 static int rip_check (pid_t pid, const char *link)
389 assert (pid != getpid ());
391 return strcmp (link, childptyname) == 0;
399 static struct pid *pid_list;
401 static int pid_found (pid_t pid)
405 for (entry = pid_list; entry != NULL; entry = entry->next)
406 if (entry->pid == pid)
411 static void pid_record (pid_t pid)
418 entry = malloc (sizeof (*entry));
421 fprintf (stderr, "%s: malloc: %m\n", progname);
425 entry->next = pid_list;
429 static void pid_forall (void (*func) (pid_t pid))
433 for (entry = pid_list; entry != NULL; entry = entry->next)
434 (*func) (entry->pid);
437 /* Returns 0 on failure. */
438 static pid_t pid_get_parent (pid_t pid)
445 if (snprintf (fname, sizeof fname, "/proc/%d/status", (int) pid) < 0)
447 perror ("snprintf(3)");
450 f = fopen (fname, "r");
455 while (errno = 0, fgets (line, sizeof line, f) == line)
457 if (strncmp (line, "PPid:\t", sizeof "PPid:\t" - 1) != 0)
459 retval = atoi (line + sizeof "PPid:\t" - 1);
465 fprintf (stderr, "%s: fgets (\"%s\"): %m\n", progname, fname);
470 fprintf (stderr, "%s: fclose (\"%s\"): %m\n", progname, fname);
476 static void killtree (pid_t pid);
478 static void killtree_pid_fs_scan (pid_t pid, void *data)
480 pid_t parent_pid = *(pid_t *) data;
486 if (pid_get_parent (pid) != parent_pid)
492 static void killtree (pid_t pid)
495 pid_fs_scan (killtree_pid_fs_scan, &pid);
498 static void rip_pid_fs_scan (pid_t pid, void *data)
502 /* Shouldn't happen. */
503 if (pid == getpid ())
506 /* Check both PGID and the stale file descriptors. */
507 pgid = getpgid (pid);
509 || fd_fs_scan (pid, rip_check) != 0)
513 static void killproc (pid_t pid)
517 cmdline = read_cmdline (pid);
518 /* Avoid printing the message for already gone processes. */
519 if (kill (pid, 0) != 0 && errno == ESRCH)
523 fprintf (stderr, "%s: Killed -9 orphan PID %d: %s\n", progname, (int) pid, cmdline);
524 if (kill (pid, SIGKILL))
527 fprintf (stderr, "%s: kill (%d, SIGKILL): %m\n", progname, (int) pid);
530 /* Do not waitpid(2) as it cannot be our direct descendant and it gets
531 cleaned up by init(8). */
534 pid_got = waitpid (pid, NULL, 0);
537 fprintf (stderr, "%s: waitpid (%d) != %d: %m\n", progname,
538 (int) pid, (int) pid_got);
546 pid_fs_scan (rip_pid_fs_scan, NULL);
547 pid_forall (killproc);
550 int main (int argc, char **argv)
554 if (argc < 2 || strcmp (argv[1], "-h") == 0
555 || strcmp (argv[1], "--help") == 0)
557 fputs ("Syntax: orphanripper <execvp(3) commandline>\n", stdout);