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_chld_hit = 0;
51 static void signal_chld (int signo)
56 static volatile int signal_alrm_hit = 0;
58 static void signal_alrm (int signo)
63 static char childptyname[LINE_MAX];
66 static void print_child_error (const char *reason, char **argv)
70 fprintf (stderr, "%s: %d %s:", progname, (int) child, reason);
71 for (sp = argv; *sp != NULL; sp++)
79 static int read_out (int amaster)
84 buf_got = read (amaster, buf, sizeof buf);
87 /* Weird but at least after POLLHUP we get EIO instead of just EOF. */
88 if (buf_got == -1 && errno == EIO)
92 perror ("read (amaster)");
95 if (write (STDOUT_FILENO, buf, buf_got) != buf_got)
103 static int spawn (char **argv, int timeout)
106 int status, amaster, i, rc;
107 struct sigaction act;
109 struct termios termios;
112 /* We do not use signal(2) to be sure we do not have SA_RESTART. */
113 memset (&act, 0, sizeof (act));
114 act.sa_handler = signal_chld;
115 i = sigemptyset (&act.sa_mask);
117 act.sa_flags = 0; /* !SA_RESTART */
118 i = sigaction (SIGCHLD, &act, NULL);
121 i = sigemptyset (&set);
123 i = sigaddset (&set, SIGCHLD);
125 i = sigprocmask (SIG_SETMASK, &set, NULL);
128 /* With TERMP passed as NULL we get "\n" -> "\r\n". */
129 termios.c_iflag = IGNBRK | IGNPAR;
131 termios.c_cflag = CS8 | CREAD | CLOCAL | HUPCL | B9600;
132 termios.c_lflag = IEXTEN | NOFLSH;
133 memset (termios.c_cc, _POSIX_VDISABLE, sizeof (termios.c_cc));
134 termios.c_cc[VTIME] = 0;
135 termios.c_cc[VMIN ] = 1;
136 cfmakeraw (&termios);
138 /* Workaround a readline deadlock bug in _get_tty_settings(). */
139 termios.c_lflag &= ~FLUSHO;
141 child = forkpty (&amaster, childptyname, &termios, NULL);
145 perror ("forkpty(3)");
148 /* Do not replace STDIN as inferiors query its termios. */
150 i = close (STDIN_FILENO);
152 i = open ("/dev/null", O_RDONLY);
153 assert (i == STDIN_FILENO);
156 /* Do not setpgrp(2) in the parent process as the process-group
157 is shared for the whole sh(1) pipeline we could be a part
158 of. The process-group is set according to PID of the first
159 command in the pipeline.
160 We would rip even vi(1) in the case of:
161 ./orphanripper sh -c 'sleep 1&' | vi -
163 /* Do not setpgrp(2) as our pty would not be ours and we would
164 get `SIGSTOP' later, particularly after spawning gdb(1).
165 setsid(3) was already executed by forkpty(3) and it would fail if
167 if (getpid() != getpgrp ())
169 perror ("getpgrp(2)");
172 execvp (argv[0], argv);
173 perror ("execvp(2)");
178 i = fcntl (amaster, F_SETFL, O_RDWR | O_NONBLOCK);
181 perror ("fcntl (amaster, F_SETFL, O_NONBLOCK)");
185 /* We do not use signal(2) to be sure we do not have SA_RESTART. */
186 act.sa_handler = signal_alrm;
187 i = sigaction (SIGALRM, &act, NULL);
190 alarm_orig = alarm (timeout);
191 assert (alarm_orig == 0);
193 i = sigemptyset (&set);
196 while (!signal_alrm_hit)
198 struct pollfd pollfd;
201 pollfd.events = POLLIN;
202 i = ppoll (&pollfd, 1, NULL, &set);
203 if (i == -1 && errno == EINTR && signal_chld_hit)
206 /* Data available? Process it first. */
207 if (pollfd.revents & POLLIN)
209 if (!read_out (amaster))
211 fprintf (stderr, "%s: Unexpected EOF\n", progname);
215 if (pollfd.revents & POLLHUP)
217 if ((pollfd.revents &= ~POLLIN) != 0)
219 fprintf (stderr, "%s: ppoll(2): revents 0x%x\n", progname,
220 (unsigned) pollfd.revents);
230 i = kill (child, SIGKILL);
236 /* WNOHANG still could fail. */
237 child_got = waitpid (child, &status, 0);
238 if (child != child_got)
240 fprintf (stderr, "waitpid (%d) = %d: %m\n", (int) child, (int) child_got);
247 if (asprintf (&buf, "Timed out after %d seconds", timeout) != -1)
249 print_child_error (buf, argv);
254 else if (WIFEXITED (status))
255 rc = WEXITSTATUS (status);
256 else if (WIFSIGNALED (status))
258 print_child_error (strsignal (WTERMSIG (status)), argv);
259 rc = 128 + WTERMSIG (status);
261 else if (WIFSTOPPED (status))
263 fprintf (stderr, "waitpid (%d): WIFSTOPPED - WSTOPSIG is %d\n",
264 (int) child, WSTOPSIG (status));
269 fprintf (stderr, "waitpid (%d): !WIFEXITED (%d)\n", (int) child, status);
273 /* In the POLLHUP case we may not have seen SIGCHLD so far. */
274 i = sigprocmask (SIG_SETMASK, &set, NULL);
277 assert (signal_chld_hit != 0);
279 /* Do not unset O_NONBLOCK as a stale child (the whole purpose of this
280 program) having open its output pty would block us in read_out. */
282 i = fcntl (amaster, F_SETFL, O_RDONLY /* !O_NONBLOCK */);
285 perror ("fcntl (amaster, F_SETFL, O_RDONLY /* !O_NONBLOCK */)");
290 while (read_out (amaster));
292 /* Do not close the master FD as the child would have `/dev/pts/23 (deleted)'
293 entries which are not expected (and expecting ` (deleted)' would be
299 perror ("close (forkpty ()'s amaster)");
307 /* Detected commandline may look weird due to a race:
309 ./orphanripper sh -c 'sleep 1&' &
312 ./orphanripper: Killed -9 orphan PID 29612 (PGID 29611): sleep 1
313 Raced output (sh(1) child still did not update its argv[]):
315 ./orphanripper: Killed -9 orphan PID 29615 (PGID 29614): sh -c sleep 1&
316 We could delay a bit before ripping the children. */
317 static const char *read_cmdline (pid_t pid)
319 char cmdline_fname[32];
320 static char cmdline[LINE_MAX];
325 if (snprintf (cmdline_fname, sizeof cmdline_fname, "/proc/%d/cmdline",
328 fd = open (cmdline_fname, O_RDONLY);
331 /* It may have already exited - ENOENT. */
333 fprintf (stderr, "%s: open (\"%s\"): %m\n", progname, cmdline_fname);
337 got = read (fd, cmdline, sizeof (cmdline) - 1);
339 fprintf (stderr, "%s: read (\"%s\"): %m\n", progname,
342 fprintf (stderr, "%s: close (\"%s\"): %m\n", progname,
346 /* Convert '\0' argument delimiters to spaces. */
347 for (s = cmdline; s < cmdline + got; s++)
350 /* Trim the trailing spaces (typically single '\0'->' '). */
351 while (s > cmdline && isspace (s[-1]))
357 static int dir_scan (const char *dirname,
358 int (*callback) (struct dirent *dirent, const char *pathname))
361 struct dirent *dirent;
364 dir = opendir (dirname);
367 if (errno == EACCES || errno == ENOENT)
369 fprintf (stderr, "%s: opendir (\"%s\"): %m\n", progname, dirname);
372 while ((errno = 0, dirent = readdir (dir)))
374 char pathname[LINE_MAX];
377 pathname_len = snprintf (pathname, sizeof pathname, "%s/%s",
378 dirname, dirent->d_name);
379 if (pathname_len <= 0 || pathname_len >= (int) sizeof pathname)
381 fprintf (stderr, "entry file name too long: `%s' / `%s'\n",
382 dirname, dirent->d_name);
385 /* RHEL-4.5 on s390x never fills in D_TYPE. */
386 if (dirent->d_type == DT_UNKNOWN)
391 /* We are not interested in the /proc/PID/fd/ links targets. */
392 i = lstat (pathname, &statbuf);
395 if (errno == EACCES || errno == ENOENT)
397 fprintf (stderr, "%s: stat (\"%s\"): %m\n", progname, pathname);
400 if (S_ISDIR (statbuf.st_mode))
401 dirent->d_type = DT_DIR;
402 if (S_ISLNK (statbuf.st_mode))
403 dirent->d_type = DT_LNK;
404 /* No other D_TYPE types used in this code. */
406 rc = (*callback) (dirent, pathname);
415 fprintf (stderr, "%s: readdir (\"%s\"): %m\n", progname, dirname);
418 if (closedir (dir) != 0)
420 fprintf (stderr, "%s: closedir (\"%s\"): %m\n", progname, dirname);
426 static int fd_fs_scan (pid_t pid, int (*func) (pid_t pid, const char *link))
430 if (snprintf (dirname, sizeof dirname, "/proc/%d/fd", (int) pid) < 0)
432 perror ("snprintf(3)");
436 int callback (struct dirent *dirent, const char *pathname)
441 if ((dirent->d_type != DT_DIR && dirent->d_type != DT_LNK)
442 || (dirent->d_type == DT_DIR && strcmp (dirent->d_name, ".") != 0
443 && strcmp (dirent->d_name, "..") != 0)
444 || (dirent->d_type == DT_LNK && strspn (dirent->d_name, "0123456789")
445 != strlen (dirent->d_name)))
447 fprintf (stderr, "Unexpected entry \"%s\" (d_type %u)"
448 " on readdir (\"%s\"): %m\n",
449 dirent->d_name, (unsigned) dirent->d_type, dirname);
452 if (dirent->d_type == DT_DIR)
454 buf_len = readlink (pathname, buf, sizeof buf - 1);
455 if (buf_len <= 0 || buf_len >= (ssize_t) sizeof buf - 1)
457 if (errno != ENOENT && errno != EACCES)
458 fprintf (stderr, "Error reading link \"%s\": %m\n", pathname);
462 return (*func) (pid, buf);
465 return dir_scan (dirname, callback);
468 static void pid_fs_scan (void (*func) (pid_t pid, void *data), void *data)
470 int callback (struct dirent *dirent, const char *pathname)
472 if (dirent->d_type != DT_DIR
473 || strspn (dirent->d_name, "0123456789") != strlen (dirent->d_name))
475 (*func) (atoi (dirent->d_name), data);
479 dir_scan ("/proc", callback);
482 static int rip_check_ptyname (pid_t pid, const char *link)
484 assert (pid != getpid ());
486 return strcmp (link, childptyname) == 0;
494 static struct pid *pid_list;
496 static int pid_found (pid_t pid)
500 for (entry = pid_list; entry != NULL; entry = entry->next)
501 if (entry->pid == pid)
506 /* Single pass is not enough, a (multithreaded) process was seen to survive.
507 Repeated killing of the same process is not enough, zombies can be killed.
509 static int cleanup_acted;
511 static void pid_record (pid_t pid)
519 entry = malloc (sizeof (*entry));
522 fprintf (stderr, "%s: malloc: %m\n", progname);
526 entry->next = pid_list;
530 static void pid_forall (void (*func) (pid_t pid))
534 for (entry = pid_list; entry != NULL; entry = entry->next)
535 (*func) (entry->pid);
538 /* Returns 0 on failure. */
539 static pid_t pid_get_parent (pid_t pid)
546 if (snprintf (fname, sizeof fname, "/proc/%d/status", (int) pid) < 0)
548 perror ("snprintf(3)");
551 f = fopen (fname, "r");
556 while (errno = 0, fgets (line, sizeof line, f) == line)
558 if (strncmp (line, "PPid:\t", sizeof "PPid:\t" - 1) != 0)
560 retval = atoi (line + sizeof "PPid:\t" - 1);
566 fprintf (stderr, "%s: fgets (\"%s\"): %m\n", progname, fname);
571 fprintf (stderr, "%s: fclose (\"%s\"): %m\n", progname, fname);
577 static void killtree (pid_t pid);
579 static void killtree_pid_fs_scan (pid_t pid, void *data)
581 pid_t parent_pid = *(pid_t *) data;
583 /* Do not optimize it as we could miss some newly spawned processes.
584 Always traverse all the leaves. */
591 if (pid_get_parent (pid) != parent_pid)
597 static void killtree (pid_t pid)
600 pid_fs_scan (killtree_pid_fs_scan, &pid);
603 static void rip_pid_fs_scan (pid_t pid, void *data)
607 /* Shouldn't happen. */
608 if (pid == getpid ())
611 /* Check both PGID and the stale file descriptors. */
612 pgid = getpgid (pid);
614 || fd_fs_scan (pid, rip_check_ptyname) != 0)
618 static void killproc (pid_t pid)
622 cmdline = read_cmdline (pid);
623 /* Avoid printing the message for already gone processes. */
624 if (kill (pid, 0) != 0 && errno == ESRCH)
628 fprintf (stderr, "%s: Killed -9 orphan PID %d: %s\n", progname, (int) pid, cmdline);
629 if (kill (pid, SIGKILL) == 0)
631 else if (errno != ESRCH)
632 fprintf (stderr, "%s: kill (%d, SIGKILL): %m\n", progname, (int) pid);
633 /* RHEL-3 kernels cannot SIGKILL a `T (stopped)' process. */
635 /* Do not waitpid(2) as it cannot be our direct descendant and it gets
636 cleaned up by init(8). */
639 pid_got = waitpid (pid, NULL, 0);
642 fprintf (stderr, "%s: waitpid (%d) != %d: %m\n", progname,
643 (int) pid, (int) pid_got);
649 static void rip (void)
655 usleep (1000000 / 10);
657 pid_fs_scan (rip_pid_fs_scan, NULL);
658 pid_forall (killproc);
660 while (cleanup_acted);
663 int main (int argc, char **argv)
671 if (argc < 1 || strcmp (*argv, "-h") == 0
672 || strcmp (*argv, "--help") == 0)
674 puts ("Syntax: orphanripper [-t <seconds>] <execvp(3) commandline>");
677 if ((*argv)[0] == '-' && (*argv)[1] == 't')
679 char *timeout_s = NULL;
683 else if (isdigit ((*argv)[2]))
684 timeout_s = (*argv) + 2;
685 if (timeout_s != NULL)
691 l = strtol (timeout_s, &endptr, 0);
693 if ((endptr != NULL && *endptr != 0) || timeout < 0 || timeout != l)
695 fprintf (stderr, "%s: Invalid timeout value: %s\n", progname,
702 rc = spawn (argv, timeout);