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 i = fcntl (amaster, F_SETFL, O_RDONLY /* !O_NONBLOCK */);
282 perror ("fcntl (amaster, F_SETFL, O_RDONLY /* !O_NONBLOCK */)");
286 while (read_out (amaster));
288 /* Do not close the master FD as the child would have `/dev/pts/23 (deleted)'
289 entries which are not expected (and expecting ` (deleted)' would be
295 perror ("close (forkpty ()'s amaster)");
303 /* Detected commandline may look weird due to a race:
305 ./orphanripper sh -c 'sleep 1&' &
308 ./orphanripper: Killed -9 orphan PID 29612 (PGID 29611): sleep 1
309 Raced output (sh(1) child still did not update its argv[]):
311 ./orphanripper: Killed -9 orphan PID 29615 (PGID 29614): sh -c sleep 1&
312 We could delay a bit before ripping the children. */
313 static const char *read_cmdline (pid_t pid)
315 char cmdline_fname[32];
316 static char cmdline[LINE_MAX];
321 if (snprintf (cmdline_fname, sizeof cmdline_fname, "/proc/%d/cmdline",
324 fd = open (cmdline_fname, O_RDONLY);
327 /* It may have already exited - ENOENT. */
329 fprintf (stderr, "%s: open (\"%s\"): %m\n", progname, cmdline_fname);
333 got = read (fd, cmdline, sizeof (cmdline) - 1);
335 fprintf (stderr, "%s: read (\"%s\"): %m\n", progname,
338 fprintf (stderr, "%s: close (\"%s\"): %m\n", progname,
342 /* Convert '\0' argument delimiters to spaces. */
343 for (s = cmdline; s < cmdline + got; s++)
346 /* Trim the trailing spaces (typically single '\0'->' '). */
347 while (s > cmdline && isspace (s[-1]))
353 static int dir_scan (const char *dirname,
354 int (*callback) (struct dirent *dirent, const char *pathname))
357 struct dirent *dirent;
360 dir = opendir (dirname);
363 if (errno == EACCES || errno == ENOENT)
365 fprintf (stderr, "%s: opendir (\"%s\"): %m\n", progname, dirname);
368 while ((errno = 0, dirent = readdir (dir)))
370 char pathname[LINE_MAX];
373 pathname_len = snprintf (pathname, sizeof pathname, "%s/%s",
374 dirname, dirent->d_name);
375 if (pathname_len <= 0 || pathname_len >= (int) sizeof pathname)
377 fprintf (stderr, "entry file name too long: `%s' / `%s'\n",
378 dirname, dirent->d_name);
381 /* RHEL-4.5 on s390x never fills in D_TYPE. */
382 if (dirent->d_type == DT_UNKNOWN)
387 /* We are not interested in the /proc/PID/fd/ links targets. */
388 i = lstat (pathname, &statbuf);
391 if (errno == EACCES || errno == ENOENT)
393 fprintf (stderr, "%s: stat (\"%s\"): %m\n", progname, pathname);
396 if (S_ISDIR (statbuf.st_mode))
397 dirent->d_type = DT_DIR;
398 if (S_ISLNK (statbuf.st_mode))
399 dirent->d_type = DT_LNK;
400 /* No other D_TYPE types used in this code. */
402 rc = (*callback) (dirent, pathname);
411 fprintf (stderr, "%s: readdir (\"%s\"): %m\n", progname, dirname);
414 if (closedir (dir) != 0)
416 fprintf (stderr, "%s: closedir (\"%s\"): %m\n", progname, dirname);
422 static int fd_fs_scan (pid_t pid, int (*func) (pid_t pid, const char *link))
426 if (snprintf (dirname, sizeof dirname, "/proc/%d/fd", (int) pid) < 0)
428 perror ("snprintf(3)");
432 int callback (struct dirent *dirent, const char *pathname)
437 if ((dirent->d_type != DT_DIR && dirent->d_type != DT_LNK)
438 || (dirent->d_type == DT_DIR && strcmp (dirent->d_name, ".") != 0
439 && strcmp (dirent->d_name, "..") != 0)
440 || (dirent->d_type == DT_LNK && strspn (dirent->d_name, "0123456789")
441 != strlen (dirent->d_name)))
443 fprintf (stderr, "Unexpected entry \"%s\" (d_type %u)"
444 " on readdir (\"%s\"): %m\n",
445 dirent->d_name, (unsigned) dirent->d_type, dirname);
448 if (dirent->d_type == DT_DIR)
450 buf_len = readlink (pathname, buf, sizeof buf - 1);
451 if (buf_len <= 0 || buf_len >= (ssize_t) sizeof buf - 1)
453 if (errno != ENOENT && errno != EACCES)
454 fprintf (stderr, "Error reading link \"%s\": %m\n", pathname);
458 return (*func) (pid, buf);
461 return dir_scan (dirname, callback);
464 static void pid_fs_scan (void (*func) (pid_t pid, void *data), void *data)
466 int callback (struct dirent *dirent, const char *pathname)
468 if (dirent->d_type != DT_DIR
469 || strspn (dirent->d_name, "0123456789") != strlen (dirent->d_name))
471 (*func) (atoi (dirent->d_name), data);
475 dir_scan ("/proc", callback);
478 static int rip_check_ptyname (pid_t pid, const char *link)
480 assert (pid != getpid ());
482 return strcmp (link, childptyname) == 0;
490 static struct pid *pid_list;
492 static int pid_found (pid_t pid)
496 for (entry = pid_list; entry != NULL; entry = entry->next)
497 if (entry->pid == pid)
502 /* Single pass is not enough, a (multithreaded) process was seen to survive.
503 Repeated killing of the same process is not enough, zombies can be killed.
505 static int cleanup_acted;
507 static void pid_record (pid_t pid)
515 entry = malloc (sizeof (*entry));
518 fprintf (stderr, "%s: malloc: %m\n", progname);
522 entry->next = pid_list;
526 static void pid_forall (void (*func) (pid_t pid))
530 for (entry = pid_list; entry != NULL; entry = entry->next)
531 (*func) (entry->pid);
534 /* Returns 0 on failure. */
535 static pid_t pid_get_parent (pid_t pid)
542 if (snprintf (fname, sizeof fname, "/proc/%d/status", (int) pid) < 0)
544 perror ("snprintf(3)");
547 f = fopen (fname, "r");
552 while (errno = 0, fgets (line, sizeof line, f) == line)
554 if (strncmp (line, "PPid:\t", sizeof "PPid:\t" - 1) != 0)
556 retval = atoi (line + sizeof "PPid:\t" - 1);
562 fprintf (stderr, "%s: fgets (\"%s\"): %m\n", progname, fname);
567 fprintf (stderr, "%s: fclose (\"%s\"): %m\n", progname, fname);
573 static void killtree (pid_t pid);
575 static void killtree_pid_fs_scan (pid_t pid, void *data)
577 pid_t parent_pid = *(pid_t *) data;
579 /* Do not optimize it as we could miss some newly spawned processes.
580 Always traverse all the leaves. */
587 if (pid_get_parent (pid) != parent_pid)
593 static void killtree (pid_t pid)
596 pid_fs_scan (killtree_pid_fs_scan, &pid);
599 static void rip_pid_fs_scan (pid_t pid, void *data)
603 /* Shouldn't happen. */
604 if (pid == getpid ())
607 /* Check both PGID and the stale file descriptors. */
608 pgid = getpgid (pid);
610 || fd_fs_scan (pid, rip_check_ptyname) != 0)
614 static void killproc (pid_t pid)
618 cmdline = read_cmdline (pid);
619 /* Avoid printing the message for already gone processes. */
620 if (kill (pid, 0) != 0 && errno == ESRCH)
624 fprintf (stderr, "%s: Killed -9 orphan PID %d: %s\n", progname, (int) pid, cmdline);
625 if (kill (pid, SIGKILL) == 0)
627 else if (errno != ESRCH)
628 fprintf (stderr, "%s: kill (%d, SIGKILL): %m\n", progname, (int) pid);
629 /* RHEL-3 kernels cannot SIGKILL a `T (stopped)' process. */
631 /* Do not waitpid(2) as it cannot be our direct descendant and it gets
632 cleaned up by init(8). */
635 pid_got = waitpid (pid, NULL, 0);
638 fprintf (stderr, "%s: waitpid (%d) != %d: %m\n", progname,
639 (int) pid, (int) pid_got);
645 static void rip (void)
651 usleep (1000000 / 10);
653 pid_fs_scan (rip_pid_fs_scan, NULL);
654 pid_forall (killproc);
656 while (cleanup_acted);
659 int main (int argc, char **argv)
667 if (argc < 1 || strcmp (*argv, "-h") == 0
668 || strcmp (*argv, "--help") == 0)
670 puts ("Syntax: orphanripper [-t <seconds>] <execvp(3) commandline>");
673 if ((*argv)[0] == '-' && (*argv)[1] == 't')
675 char *timeout_s = NULL;
679 else if (isdigit ((*argv)[2]))
680 timeout_s = (*argv) + 2;
681 if (timeout_s != NULL)
687 l = strtol (timeout_s, &endptr, 0);
689 if ((endptr != NULL && *endptr != 0) || timeout < 0 || timeout != l)
691 fprintf (stderr, "%s: Invalid timeout value: %s\n", progname,
698 rc = spawn (argv, timeout);