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>
46 #define LENGTH(x) (sizeof (x) / sizeof (*(x)))
48 static const char *progname;
50 static volatile pid_t child;
52 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];
65 static void print_child_error (const char *reason, char **argv)
69 fprintf (stderr, "%s: %d %s:", progname, (int) child, reason);
70 for (sp = argv; *sp != NULL; sp++)
78 static int read_out (int amaster)
83 buf_got = read (amaster, buf, sizeof buf);
86 /* Weird but at least after POLLHUP we get EIO instead of just EOF. */
87 if (buf_got == -1 && errno == EIO)
89 if (buf_got == -1 && errno == EAGAIN)
93 perror ("read (amaster)");
96 if (write (STDOUT_FILENO, buf, buf_got) != buf_got)
104 /* kill (child, 0) ==0 sometimes even when CHILD's state is already Z. */
106 static int child_exited (void)
113 snprintf (buf, sizeof (buf), "/proc/%ld/stat", (long) child);
114 fd = open (buf, O_RDONLY);
117 perror ("open (/proc/CHILD/stat)");
120 got = read (fd, buf, sizeof(buf));
123 perror ("read (/proc/CHILD/stat)");
128 perror ("close (/proc/CHILD/stat)");
131 i = sscanf (buf, "%*d%*s%ms", &state);
134 perror ("sscanf (/proc/CHILD/stat)");
137 retval = strcmp (state, "Z") == 0;
142 static int spawn (char **argv, int timeout)
145 int status, amaster, i, rc;
146 struct sigaction act;
148 struct termios termios;
151 /* We do not use signal(2) to be sure we do not have SA_RESTART. */
152 memset (&act, 0, sizeof (act));
153 act.sa_handler = signal_chld;
154 i = sigemptyset (&act.sa_mask);
156 act.sa_flags = 0; /* !SA_RESTART */
157 i = sigaction (SIGCHLD, &act, NULL);
160 i = sigemptyset (&set);
162 i = sigaddset (&set, SIGCHLD);
164 i = sigprocmask (SIG_SETMASK, &set, NULL);
167 /* With TERMP passed as NULL we get "\n" -> "\r\n". */
168 termios.c_iflag = IGNBRK | IGNPAR;
170 termios.c_cflag = CS8 | CREAD | CLOCAL | HUPCL | B9600;
171 termios.c_lflag = IEXTEN | NOFLSH;
172 memset (termios.c_cc, _POSIX_VDISABLE, sizeof (termios.c_cc));
173 termios.c_cc[VTIME] = 0;
174 termios.c_cc[VMIN ] = 1;
175 cfmakeraw (&termios);
177 /* Workaround a readline deadlock bug in _get_tty_settings(). */
178 termios.c_lflag &= ~FLUSHO;
180 child = forkpty (&amaster, childptyname, &termios, NULL);
184 perror ("forkpty(3)");
187 /* Do not replace STDIN as inferiors query its termios. */
189 i = close (STDIN_FILENO);
191 i = open ("/dev/null", O_RDONLY);
192 assert (i == STDIN_FILENO);
195 i = sigemptyset (&set);
197 i = sigprocmask (SIG_SETMASK, &set, NULL);
200 /* Do not setpgrp(2) in the parent process as the process-group
201 is shared for the whole sh(1) pipeline we could be a part
202 of. The process-group is set according to PID of the first
203 command in the pipeline.
204 We would rip even vi(1) in the case of:
205 ./orphanripper sh -c 'sleep 1&' | vi -
207 /* Do not setpgrp(2) as our pty would not be ours and we would
208 get `SIGSTOP' later, particularly after spawning gdb(1).
209 setsid(3) was already executed by forkpty(3) and it would fail if
211 if (getpid() != getpgrp ())
213 perror ("getpgrp(2)");
216 execvp (argv[0], argv);
217 perror ("execvp(2)");
222 i = fcntl (amaster, F_SETFL, O_RDWR | O_NONBLOCK);
225 perror ("fcntl (amaster, F_SETFL, O_NONBLOCK)");
229 /* We do not use signal(2) to be sure we do not have SA_RESTART. */
230 act.sa_handler = signal_alrm;
231 i = sigaction (SIGALRM, &act, NULL);
234 alarm_orig = alarm (timeout);
235 assert (alarm_orig == 0);
237 i = sigemptyset (&set);
240 while (!signal_alrm_hit)
242 struct pollfd pollfd;
245 pollfd.events = POLLIN;
246 i = ppoll (&pollfd, 1, NULL, &set);
247 if (i == -1 && errno == EINTR)
251 /* Non-CHILD child may have exited. */
255 /* Data available? Process it first. */
256 if (pollfd.revents & POLLIN)
258 if (!read_out (amaster))
260 fprintf (stderr, "%s: Unexpected EOF\n", progname);
264 if (pollfd.revents & POLLHUP)
266 if ((pollfd.revents &= ~POLLIN) != 0)
268 fprintf (stderr, "%s: ppoll(2): revents 0x%x\n", progname,
269 (unsigned) pollfd.revents);
279 i = kill (child, SIGKILL);
285 /* WNOHANG still could fail. */
286 child_got = waitpid (child, &status, 0);
287 if (child != child_got)
289 fprintf (stderr, "waitpid (%d) = %d: %m\n", (int) child, (int) child_got);
296 if (asprintf (&buf, "Timed out after %d seconds", timeout) != -1)
298 print_child_error (buf, argv);
303 else if (WIFEXITED (status))
304 rc = WEXITSTATUS (status);
305 else if (WIFSIGNALED (status))
307 print_child_error (strsignal (WTERMSIG (status)), argv);
308 rc = 128 + WTERMSIG (status);
310 else if (WIFSTOPPED (status))
312 fprintf (stderr, "waitpid (%d): WIFSTOPPED - WSTOPSIG is %d\n",
313 (int) child, WSTOPSIG (status));
318 fprintf (stderr, "waitpid (%d): !WIFEXITED (%d)\n", (int) child, status);
322 /* Not used in fact. */
323 i = sigprocmask (SIG_SETMASK, &set, NULL);
326 /* Do not unset O_NONBLOCK as a stale child (the whole purpose of this
327 program) having open its output pty would block us in read_out. */
329 i = fcntl (amaster, F_SETFL, O_RDONLY /* !O_NONBLOCK */);
332 perror ("fcntl (amaster, F_SETFL, O_RDONLY /* !O_NONBLOCK */)");
337 while (read_out (amaster));
339 /* Do not close the master FD as the child would have `/dev/pts/23 (deleted)'
340 entries which are not expected (and expecting ` (deleted)' would be
346 perror ("close (forkpty ()'s amaster)");
354 /* Detected commandline may look weird due to a race:
356 ./orphanripper sh -c 'sleep 1&' &
359 ./orphanripper: Killed -9 orphan PID 29612 (PGID 29611): sleep 1
360 Raced output (sh(1) child still did not update its argv[]):
362 ./orphanripper: Killed -9 orphan PID 29615 (PGID 29614): sh -c sleep 1&
363 We could delay a bit before ripping the children. */
364 static const char *read_cmdline (pid_t pid)
366 char cmdline_fname[32];
367 static char cmdline[LINE_MAX];
372 if (snprintf (cmdline_fname, sizeof cmdline_fname, "/proc/%d/cmdline",
375 fd = open (cmdline_fname, O_RDONLY);
378 /* It may have already exited - ENOENT. */
380 fprintf (stderr, "%s: open (\"%s\"): %m\n", progname, cmdline_fname);
384 got = read (fd, cmdline, sizeof (cmdline) - 1);
386 fprintf (stderr, "%s: read (\"%s\"): %m\n", progname,
389 fprintf (stderr, "%s: close (\"%s\"): %m\n", progname,
393 /* Convert '\0' argument delimiters to spaces. */
394 for (s = cmdline; s < cmdline + got; s++)
397 /* Trim the trailing spaces (typically single '\0'->' '). */
398 while (s > cmdline && isspace (s[-1]))
404 static int dir_scan (const char *dirname,
405 int (*callback) (struct dirent *dirent, const char *pathname))
408 struct dirent *dirent;
411 dir = opendir (dirname);
414 if (errno == EACCES || errno == ENOENT)
416 fprintf (stderr, "%s: opendir (\"%s\"): %m\n", progname, dirname);
419 while ((errno = 0, dirent = readdir (dir)))
421 char pathname[LINE_MAX];
424 pathname_len = snprintf (pathname, sizeof pathname, "%s/%s",
425 dirname, dirent->d_name);
426 if (pathname_len <= 0 || pathname_len >= (int) sizeof pathname)
428 fprintf (stderr, "entry file name too long: `%s' / `%s'\n",
429 dirname, dirent->d_name);
432 /* RHEL-4.5 on s390x never fills in D_TYPE. */
433 if (dirent->d_type == DT_UNKNOWN)
438 /* We are not interested in the /proc/PID/fd/ links targets. */
439 i = lstat (pathname, &statbuf);
442 if (errno == EACCES || errno == ENOENT)
444 fprintf (stderr, "%s: stat (\"%s\"): %m\n", progname, pathname);
447 if (S_ISDIR (statbuf.st_mode))
448 dirent->d_type = DT_DIR;
449 if (S_ISLNK (statbuf.st_mode))
450 dirent->d_type = DT_LNK;
451 /* No other D_TYPE types used in this code. */
453 rc = (*callback) (dirent, pathname);
462 fprintf (stderr, "%s: readdir (\"%s\"): %m\n", progname, dirname);
465 if (closedir (dir) != 0)
467 fprintf (stderr, "%s: closedir (\"%s\"): %m\n", progname, dirname);
473 static int fd_fs_scan (pid_t pid, int (*func) (pid_t pid, const char *link))
477 if (snprintf (dirname, sizeof dirname, "/proc/%d/fd", (int) pid) < 0)
479 perror ("snprintf(3)");
483 int callback (struct dirent *dirent, const char *pathname)
488 if ((dirent->d_type != DT_DIR && dirent->d_type != DT_LNK)
489 || (dirent->d_type == DT_DIR && strcmp (dirent->d_name, ".") != 0
490 && strcmp (dirent->d_name, "..") != 0)
491 || (dirent->d_type == DT_LNK && strspn (dirent->d_name, "0123456789")
492 != strlen (dirent->d_name)))
494 fprintf (stderr, "Unexpected entry \"%s\" (d_type %u)"
495 " on readdir (\"%s\"): %m\n",
496 dirent->d_name, (unsigned) dirent->d_type, dirname);
499 if (dirent->d_type == DT_DIR)
501 buf_len = readlink (pathname, buf, sizeof buf - 1);
502 if (buf_len <= 0 || buf_len >= (ssize_t) sizeof buf - 1)
504 if (errno != ENOENT && errno != EACCES)
505 fprintf (stderr, "Error reading link \"%s\": %m\n", pathname);
509 return (*func) (pid, buf);
512 return dir_scan (dirname, callback);
515 static void pid_fs_scan (void (*func) (pid_t pid, void *data), void *data)
517 int callback (struct dirent *dirent, const char *pathname)
519 if (dirent->d_type != DT_DIR
520 || strspn (dirent->d_name, "0123456789") != strlen (dirent->d_name))
522 (*func) (atoi (dirent->d_name), data);
526 dir_scan ("/proc", callback);
529 static int rip_check_ptyname (pid_t pid, const char *link)
531 assert (pid != getpid ());
533 return strcmp (link, childptyname) == 0;
541 static struct pid *pid_list;
543 static int pid_found (pid_t pid)
547 for (entry = pid_list; entry != NULL; entry = entry->next)
548 if (entry->pid == pid)
553 /* Single pass is not enough, a (multithreaded) process was seen to survive.
554 Repeated killing of the same process is not enough, zombies can be killed.
556 static int cleanup_acted;
558 static void pid_record (pid_t pid)
566 entry = malloc (sizeof (*entry));
569 fprintf (stderr, "%s: malloc: %m\n", progname);
573 entry->next = pid_list;
577 static void pid_forall (void (*func) (pid_t pid))
581 for (entry = pid_list; entry != NULL; entry = entry->next)
582 (*func) (entry->pid);
585 /* Returns 0 on failure. */
586 static pid_t pid_get_parent (pid_t pid)
593 if (snprintf (fname, sizeof fname, "/proc/%d/status", (int) pid) < 0)
595 perror ("snprintf(3)");
598 f = fopen (fname, "r");
603 while (errno = 0, fgets (line, sizeof line, f) == line)
605 if (strncmp (line, "PPid:\t", sizeof "PPid:\t" - 1) != 0)
607 retval = atoi (line + sizeof "PPid:\t" - 1);
613 fprintf (stderr, "%s: fgets (\"%s\"): %m\n", progname, fname);
618 fprintf (stderr, "%s: fclose (\"%s\"): %m\n", progname, fname);
624 static void killtree (pid_t pid);
626 static void killtree_pid_fs_scan (pid_t pid, void *data)
628 pid_t parent_pid = *(pid_t *) data;
630 /* Do not optimize it as we could miss some newly spawned processes.
631 Always traverse all the leaves. */
638 if (pid_get_parent (pid) != parent_pid)
644 static void killtree (pid_t pid)
647 pid_fs_scan (killtree_pid_fs_scan, &pid);
650 static void rip_pid_fs_scan (pid_t pid, void *data)
654 /* Shouldn't happen. */
655 if (pid == getpid ())
658 /* Check both PGID and the stale file descriptors. */
659 pgid = getpgid (pid);
661 || fd_fs_scan (pid, rip_check_ptyname) != 0)
665 static void killproc (pid_t pid)
669 cmdline = read_cmdline (pid);
670 /* Avoid printing the message for already gone processes. */
671 if (kill (pid, 0) != 0 && errno == ESRCH)
675 fprintf (stderr, "%s: Killed -9 orphan PID %d: %s\n", progname, (int) pid, cmdline);
676 if (kill (pid, SIGKILL) == 0)
678 else if (errno != ESRCH)
679 fprintf (stderr, "%s: kill (%d, SIGKILL): %m\n", progname, (int) pid);
680 /* RHEL-3 kernels cannot SIGKILL a `T (stopped)' process. */
682 /* Do not waitpid(2) as it cannot be our direct descendant and it gets
683 cleaned up by init(8). */
686 pid_got = waitpid (pid, NULL, 0);
689 fprintf (stderr, "%s: waitpid (%d) != %d: %m\n", progname,
690 (int) pid, (int) pid_got);
696 static void rip (void)
702 usleep (1000000 / 10);
704 pid_fs_scan (rip_pid_fs_scan, NULL);
705 pid_forall (killproc);
707 while (cleanup_acted);
710 int main (int argc, char **argv)
718 if (argc < 1 || strcmp (*argv, "-h") == 0
719 || strcmp (*argv, "--help") == 0)
721 puts ("Syntax: orphanripper [-t <seconds>] <execvp(3) commandline>");
724 if ((*argv)[0] == '-' && (*argv)[1] == 't')
726 char *timeout_s = NULL;
730 else if (isdigit ((*argv)[2]))
731 timeout_s = (*argv) + 2;
732 if (timeout_s != NULL)
738 l = strtol (timeout_s, &endptr, 0);
740 if ((endptr != NULL && *endptr != 0) || timeout < 0 || timeout != l)
742 fprintf (stderr, "%s: Invalid timeout value: %s\n", progname,
749 rc = spawn (argv, timeout);