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 volatile int signal_alarm_hit = 0;
68 static void signal_alarm (int signo)
73 static char childptyname[LINE_MAX];
76 static void print_child_error (const char *reason, char **argv)
80 fprintf (stderr, "%s: %d %s:", progname, (int) child, reason);
81 for (sp = argv; *sp != NULL; sp++)
89 static int spawn (char **argv, int timeout)
92 int status, amaster, i, rc;
94 struct termios termios;
100 /* We do not use signal(2) to be sure we have SA_RESTART set. */
101 memset (&act, 0, sizeof (act));
102 act.sa_handler = signal_child;
103 i = sigemptyset (&act.sa_mask);
105 act.sa_flags = SA_RESTART;
106 i = sigaction (SIGCHLD, &act, NULL);
109 /* With TERMP passed as NULL we get "\n" -> "\r\n". */
110 termios.c_iflag = IGNBRK | IGNPAR;
112 termios.c_cflag = CS8 | CREAD | CLOCAL | HUPCL | B9600;
113 termios.c_lflag = IEXTEN | NOFLSH;
114 memset (termios.c_cc, _POSIX_VDISABLE, sizeof (termios.c_cc));
115 termios.c_cc[VTIME] = 0;
116 termios.c_cc[VMIN ] = 1;
117 cfmakeraw (&termios);
119 /* Workaround a readline deadlock bug in _get_tty_settings(). */
120 termios.c_lflag &= ~FLUSHO;
122 child = forkpty (&amaster, childptyname, &termios, NULL);
126 perror ("forkpty(3)");
129 i = close (pipefd[0]);
131 i = close (pipefd[1]);
134 /* Do not replace STDIN as inferiors query its termios. */
136 i = close (STDIN_FILENO);
138 i = open ("/dev/null", O_RDONLY);
139 assert (i == STDIN_FILENO);
142 /* Do not setpgrp(2) in the parent process as the process-group
143 is shared for the whole sh(1) pipeline we could be a part
144 of. The process-group is set according to PID of the first
145 command in the pipeline.
146 We would rip even vi(1) in the case of:
147 ./orphanripper sh -c 'sleep 1&' | vi -
149 /* Do not setpgrp(2) as our pty would not be ours and we would
150 get `SIGSTOP' later, particularly after spawning gdb(1).
151 setsid(3) was already executed by forkpty(3) and it would fail if
153 if (getpid() != getpgrp ())
155 perror ("getpgrp(2)");
158 execvp (argv[0], argv);
159 perror ("execvp(2)");
164 i = fcntl (amaster, F_SETFL, O_RDWR | O_NONBLOCK);
167 perror ("fcntl (amaster, F_SETFL, O_NONBLOCK)");
171 /* We do not use signal(2) to be sure we have SA_RESTART set. */
172 act.sa_handler = signal_alarm;
173 act.sa_flags &= ~SA_RESTART;
174 i = sigaction (SIGALRM, &act, NULL);
177 alarm_orig = alarm (timeout);
178 assert (alarm_orig == 0);
180 while (!signal_alarm_hit)
182 struct pollfd pollfd[2];
186 pollfd[0].fd = amaster;
187 pollfd[0].events = POLLIN;
188 pollfd[1].fd = pipefd[0];
189 pollfd[1].events = POLLIN;
190 i = poll (pollfd, LENGTH (pollfd), -1);
191 if (i == -1 && errno == EINTR)
193 /* Weird but SA_RESTART sometimes does not work. */
197 /* Data available? Process it first. */
198 if (pollfd[0].revents & POLLIN)
200 buf_got = read (amaster, buf, sizeof buf);
203 perror ("read (amaster)");
206 if (write (STDOUT_FILENO, buf, buf_got) != buf_got)
212 if (pollfd[0].revents & POLLHUP)
214 if ((pollfd[0].revents &= ~POLLIN) != 0)
216 fprintf (stderr, "%s: ppoll(2): revents 0x%x\n", progname,
217 (unsigned) pollfd[0].revents);
221 if (pollfd[1].revents & POLLHUP)
223 assert (pollfd[1].revents == 0);
226 if (signal_alarm_hit)
228 i = kill (child, SIGKILL);
234 /* WNOHANG still could fail. */
235 child_got = waitpid (child, &status, 0);
236 if (child != child_got)
238 fprintf (stderr, "waitpid (%d) = %d: %m\n", (int) child, (int) child_got);
241 if (signal_alarm_hit)
245 if (asprintf (&buf, "Timed out after %d seconds", timeout) != -1)
247 print_child_error (buf, argv);
252 else if (WIFEXITED (status))
253 rc = WEXITSTATUS (status);
254 else if (WIFSIGNALED (status))
256 print_child_error (strsignal (WTERMSIG (status)), argv);
257 rc = 128 + WTERMSIG (status);
259 else if (WIFSTOPPED (status))
261 fprintf (stderr, "waitpid (%d): WIFSTOPPED - WSTOPSIG is %d\n",
262 (int) child, WSTOPSIG (status));
267 fprintf (stderr, "waitpid (%d): !WIFEXITED (%d)\n", (int) child, status);
271 assert (signal_child_hit != 0);
273 assert (pipefd[1] == -1);
274 i = close (pipefd[0]);
277 /* Do not close the master FD as the child would have `/dev/pts/23 (deleted)'
278 entries which are not expected (and expecting ` (deleted)' would be
284 perror ("close (forkpty ()'s amaster)");
292 /* Detected commandline may look weird due to a race:
294 ./orphanripper sh -c 'sleep 1&' &
297 ./orphanripper: Killed -9 orphan PID 29612 (PGID 29611): sleep 1
298 Raced output (sh(1) child still did not update its argv[]):
300 ./orphanripper: Killed -9 orphan PID 29615 (PGID 29614): sh -c sleep 1&
301 We could delay a bit before ripping the children. */
302 static const char *read_cmdline (pid_t pid)
304 char cmdline_fname[32];
305 static char cmdline[LINE_MAX];
310 if (snprintf (cmdline_fname, sizeof cmdline_fname, "/proc/%d/cmdline",
313 fd = open (cmdline_fname, O_RDONLY);
316 /* It may have already exited - ENOENT. */
318 fprintf (stderr, "%s: open (\"%s\"): %m\n", progname, cmdline_fname);
322 got = read (fd, cmdline, sizeof (cmdline) - 1);
324 fprintf (stderr, "%s: read (\"%s\"): %m\n", progname,
327 fprintf (stderr, "%s: close (\"%s\"): %m\n", progname,
331 /* Convert '\0' argument delimiters to spaces. */
332 for (s = cmdline; s < cmdline + got; s++)
335 /* Trim the trailing spaces (typically single '\0'->' '). */
336 while (s > cmdline && isspace (s[-1]))
342 static int dir_scan (const char *dirname,
343 int (*callback) (struct dirent *dirent, const char *pathname))
346 struct dirent *dirent;
349 dir = opendir (dirname);
352 if (errno == EACCES || errno == ENOENT)
354 fprintf (stderr, "%s: opendir (\"%s\"): %m\n", progname, dirname);
357 while ((errno = 0, dirent = readdir (dir)))
359 char pathname[LINE_MAX];
362 pathname_len = snprintf (pathname, sizeof pathname, "%s/%s",
363 dirname, dirent->d_name);
364 if (pathname_len <= 0 || pathname_len >= (int) sizeof pathname)
366 fprintf (stderr, "entry file name too long: `%s' / `%s'\n",
367 dirname, dirent->d_name);
370 /* RHEL-4.5 on s390x never fills in D_TYPE. */
371 if (dirent->d_type == DT_UNKNOWN)
376 /* We are not interested in the /proc/PID/fd/ links targets. */
377 i = lstat (pathname, &statbuf);
380 if (errno == EACCES || errno == ENOENT)
382 fprintf (stderr, "%s: stat (\"%s\"): %m\n", progname, pathname);
385 if (S_ISDIR (statbuf.st_mode))
386 dirent->d_type = DT_DIR;
387 if (S_ISLNK (statbuf.st_mode))
388 dirent->d_type = DT_LNK;
389 /* No other D_TYPE types used in this code. */
391 rc = (*callback) (dirent, pathname);
400 fprintf (stderr, "%s: readdir (\"%s\"): %m\n", progname, dirname);
403 if (closedir (dir) != 0)
405 fprintf (stderr, "%s: closedir (\"%s\"): %m\n", progname, dirname);
411 static int fd_fs_scan (pid_t pid, int (*func) (pid_t pid, const char *link))
415 if (snprintf (dirname, sizeof dirname, "/proc/%d/fd", (int) pid) < 0)
417 perror ("snprintf(3)");
421 int callback (struct dirent *dirent, const char *pathname)
426 if ((dirent->d_type != DT_DIR && dirent->d_type != DT_LNK)
427 || (dirent->d_type == DT_DIR && strcmp (dirent->d_name, ".") != 0
428 && strcmp (dirent->d_name, "..") != 0)
429 || (dirent->d_type == DT_LNK && strspn (dirent->d_name, "0123456789")
430 != strlen (dirent->d_name)))
432 fprintf (stderr, "Unexpected entry \"%s\" (d_type %u)"
433 " on readdir (\"%s\"): %m\n",
434 dirent->d_name, (unsigned) dirent->d_type, dirname);
437 if (dirent->d_type == DT_DIR)
439 buf_len = readlink (pathname, buf, sizeof buf - 1);
440 if (buf_len <= 0 || buf_len >= (ssize_t) sizeof buf - 1)
442 if (errno != ENOENT && errno != EACCES)
443 fprintf (stderr, "Error reading link \"%s\": %m\n", pathname);
447 return (*func) (pid, buf);
450 return dir_scan (dirname, callback);
453 static void pid_fs_scan (void (*func) (pid_t pid, void *data), void *data)
455 int callback (struct dirent *dirent, const char *pathname)
457 if (dirent->d_type != DT_DIR
458 || strspn (dirent->d_name, "0123456789") != strlen (dirent->d_name))
460 (*func) (atoi (dirent->d_name), data);
464 dir_scan ("/proc", callback);
467 static int rip_check_ptyname (pid_t pid, const char *link)
469 assert (pid != getpid ());
471 return strcmp (link, childptyname) == 0;
479 static struct pid *pid_list;
481 static int pid_found (pid_t pid)
485 for (entry = pid_list; entry != NULL; entry = entry->next)
486 if (entry->pid == pid)
491 /* Single pass is not enough, a (multithreaded) process was seen to survive.
492 Repeated killing of the same process is not enough, zombies can be killed.
494 static int cleanup_acted;
496 static void pid_record (pid_t pid)
504 entry = malloc (sizeof (*entry));
507 fprintf (stderr, "%s: malloc: %m\n", progname);
511 entry->next = pid_list;
515 static void pid_forall (void (*func) (pid_t pid))
519 for (entry = pid_list; entry != NULL; entry = entry->next)
520 (*func) (entry->pid);
523 /* Returns 0 on failure. */
524 static pid_t pid_get_parent (pid_t pid)
531 if (snprintf (fname, sizeof fname, "/proc/%d/status", (int) pid) < 0)
533 perror ("snprintf(3)");
536 f = fopen (fname, "r");
541 while (errno = 0, fgets (line, sizeof line, f) == line)
543 if (strncmp (line, "PPid:\t", sizeof "PPid:\t" - 1) != 0)
545 retval = atoi (line + sizeof "PPid:\t" - 1);
551 fprintf (stderr, "%s: fgets (\"%s\"): %m\n", progname, fname);
556 fprintf (stderr, "%s: fclose (\"%s\"): %m\n", progname, fname);
562 static void killtree (pid_t pid);
564 static void killtree_pid_fs_scan (pid_t pid, void *data)
566 pid_t parent_pid = *(pid_t *) data;
568 /* Do not optimize it as we could miss some newly spawned processes.
569 Always traverse all the leaves. */
576 if (pid_get_parent (pid) != parent_pid)
582 static void killtree (pid_t pid)
585 pid_fs_scan (killtree_pid_fs_scan, &pid);
588 static void rip_pid_fs_scan (pid_t pid, void *data)
592 /* Shouldn't happen. */
593 if (pid == getpid ())
596 /* Check both PGID and the stale file descriptors. */
597 pgid = getpgid (pid);
599 || fd_fs_scan (pid, rip_check_ptyname) != 0)
603 static void killproc (pid_t pid)
607 cmdline = read_cmdline (pid);
608 /* Avoid printing the message for already gone processes. */
609 if (kill (pid, 0) != 0 && errno == ESRCH)
613 fprintf (stderr, "%s: Killed -9 orphan PID %d: %s\n", progname, (int) pid, cmdline);
614 if (kill (pid, SIGKILL) == 0)
616 else if (errno != ESRCH)
617 fprintf (stderr, "%s: kill (%d, SIGKILL): %m\n", progname, (int) pid);
618 /* RHEL-3 kernels cannot SIGKILL a `T (stopped)' process. */
620 /* Do not waitpid(2) as it cannot be our direct descendant and it gets
621 cleaned up by init(8). */
624 pid_got = waitpid (pid, NULL, 0);
627 fprintf (stderr, "%s: waitpid (%d) != %d: %m\n", progname,
628 (int) pid, (int) pid_got);
634 static void rip (void)
640 usleep (1000000 / 10);
642 pid_fs_scan (rip_pid_fs_scan, NULL);
643 pid_forall (killproc);
645 while (cleanup_acted);
648 int main (int argc, char **argv)
656 if (argc < 1 || strcmp (*argv, "-h") == 0
657 || strcmp (*argv, "--help") == 0)
659 puts ("Syntax: orphanripper [-t <seconds>] <execvp(3) commandline>");
662 if ((*argv)[0] == '-' && (*argv)[1] == 't')
664 char *timeout_s = NULL;
668 else if (isdigit ((*argv)[2]))
669 timeout_s = (*argv) + 2;
670 if (timeout_s != NULL)
676 l = strtol (timeout_s, &endptr, 0);
678 if ((endptr != NULL && *endptr != 0) || timeout < 0 || timeout != l)
680 fprintf (stderr, "%s: Invalid timeout value: %s\n", progname,
687 rc = spawn (argv, timeout);