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". */
91 /* Workaround a readline deadlock bug in _get_tty_settings(). */
92 termios.c_lflag &= ~FLUSHO;
94 child = forkpty (&amaster, childptyname, &termios, NULL);
98 perror ("forkpty(3)");
101 i = close (pipefd[0]);
103 i = close (pipefd[1]);
106 /* Do not replace STDIN as inferiors query its termios. */
108 i = close (STDIN_FILENO);
110 i = open ("/dev/null", O_RDONLY);
111 assert (i == STDIN_FILENO);
114 /* Do not setpgrp(2) in the parent process as the process-group
115 is shared for the whole sh(1) pipeline we could be a part
116 of. The process-group is set according to PID of the first
117 command in the pipeline.
118 We would rip even vi(1) in the case of:
119 ./orphanripper sh -c 'sleep 1&' | vi -
121 /* Do not setpgrp(2) as our pty would not be ours and we would
122 get `SIGSTOP' later, particularly after spawning gdb(1).
123 setsid(3) was already executed by forkpty(3) and it would fail if
125 if (getpid() != getpgrp ())
127 perror ("getpgrp(2)");
130 execvp (argv[1], argv + 1);
131 perror ("execvp(2)");
136 i = fcntl (amaster, F_SETFL, O_RDWR | O_NONBLOCK);
139 perror ("fcntl (amaster, F_SETFL, O_NONBLOCK)");
144 struct pollfd pollfd[2];
148 pollfd[0].fd = amaster;
149 pollfd[0].events = POLLIN;
150 pollfd[1].fd = pipefd[0];
151 pollfd[1].events = POLLIN;
152 i = poll (pollfd, LENGTH (pollfd), -1);
153 if (i == -1 && errno == EINTR)
155 /* Weird but SA_RESTART sometimes does not work. */
159 /* Data available? Process it first. */
160 if (pollfd[0].revents & POLLIN)
162 buf_got = read (amaster, buf, sizeof buf);
165 perror ("read (amaster)");
168 if (write (STDOUT_FILENO, buf, buf_got) != buf_got)
174 if (pollfd[0].revents & POLLHUP)
176 if ((pollfd[0].revents &= ~POLLIN) != 0)
178 fprintf (stderr, "%s: ppoll(2): revents 0x%x\n", progname,
179 (unsigned) pollfd[0].revents);
183 if (pollfd[1].revents & POLLHUP)
185 assert (pollfd[1].revents == 0);
187 /* WNOHANG still could fail. */
188 child_got = waitpid (child, &status, 0);
189 if (child != child_got)
191 fprintf (stderr, "waitpid (%d) = %d: %m\n", (int) child, (int) child_got);
194 if (!WIFEXITED (status))
196 fprintf (stderr, "waitpid (%d): !WIFEXITED (%d)\n", (int) child, status);
200 assert (signal_child_hit != 0);
201 assert (pipefd[1] == -1);
202 i = close (pipefd[0]);
205 /* Do not close the master FD as the child would have `/dev/pts/23 (deleted)'
206 entries which are not expected (and expecting ` (deleted)' would be
212 perror ("close (forkpty ()'s amaster)");
217 return WEXITSTATUS (status);
220 /* Detected commandline may look weird due to a race:
222 ./orphanripper sh -c 'sleep 1&' &
225 ./orphanripper: Killed -9 orphan PID 29612 (PGID 29611): sleep 1
226 Raced output (sh(1) child still did not update its argv[]):
228 ./orphanripper: Killed -9 orphan PID 29615 (PGID 29614): sh -c sleep 1&
229 We could delay a bit before ripping the children. */
230 static const char *read_cmdline (pid_t pid)
232 char cmdline_fname[32];
233 static char cmdline[LINE_MAX];
238 if (snprintf (cmdline_fname, sizeof cmdline_fname, "/proc/%d/cmdline",
241 fd = open (cmdline_fname, O_RDONLY);
244 /* It may have already exited - ENOENT. */
246 fprintf (stderr, "%s: open (\"%s\"): %m\n", progname, cmdline_fname);
250 got = read (fd, cmdline, sizeof (cmdline) - 1);
252 fprintf (stderr, "%s: read (\"%s\"): %m\n", progname,
255 fprintf (stderr, "%s: close (\"%s\"): %m\n", progname,
259 /* Convert '\0' argument delimiters to spaces. */
260 for (s = cmdline; s < cmdline + got; s++)
263 /* Trim the trailing spaces (typically single '\0'->' '). */
264 while (s > cmdline && isspace (s[-1]))
270 static int fd_fs_scan (pid_t pid, int (*func) (pid_t pid, const char *link))
273 struct dirent *dirent;
277 if (snprintf (dirname, sizeof dirname, "/proc/%d/fd", (int) pid) < 0)
279 perror ("snprintf(3)");
282 dir = opendir (dirname);
285 if (errno == EACCES || errno == ENOENT)
287 fprintf (stderr, "%s: opendir (\"%s\"): %m\n", progname, dirname);
290 while ((errno = 0, dirent = readdir (dir)))
292 char linkname[LINE_MAX], buf[LINE_MAX];
296 /* FIXME: POSIX portability. */
297 if ((dirent->d_type != DT_DIR && dirent->d_type != DT_LNK)
298 || (dirent->d_type == DT_DIR && strcmp (dirent->d_name, ".") != 0
299 && strcmp (dirent->d_name, "..") != 0)
300 || (dirent->d_type == DT_LNK && strspn (dirent->d_name, "0123456789")
301 != strlen (dirent->d_name)))
303 /* There is a race, D_TYPE may be uninitialized if stat(2) fails. */
304 if (dirent->d_type != DT_UNKNOWN)
305 fprintf (stderr, "Unexpected entry \"%s\" (d_type %u)"
306 " on readdir (\"%s\"): %m\n",
307 dirent->d_name, (unsigned) dirent->d_type, dirname);
310 if (dirent->d_type == DT_DIR)
312 linkname_len = snprintf (linkname, sizeof linkname, "%s/%s", dirname,
314 if (linkname_len <= 0 || linkname_len >= sizeof linkname)
316 fprintf (stderr, "Link content too long: `%s' / `%s'\n",
317 dirent->d_name, dirent->d_name);
320 buf_len = readlink (linkname, buf, sizeof buf - 1);
321 if (buf_len <= 0 || buf_len >= sizeof buf - 1)
323 if (errno != ENOENT && errno != EACCES)
324 fprintf (stderr, "Error reading link \"%s\": %m\n",
329 rc = (*func) (pid, buf);
338 fprintf (stderr, "%s: readdir (\"%s\"): %m\n", progname, dirname);
341 if (closedir (dir) != 0)
343 fprintf (stderr, "%s: closedir (\"%s\"): %m\n", progname, dirname);
349 static void pid_fs_scan (void (*func) (pid_t pid, void *data), void *data)
352 struct dirent *dirent;
354 dir = opendir ("/proc");
357 perror ("opendir (\"/proc\")");
360 while ((errno = 0, dirent = readdir (dir)))
362 /* FIXME: POSIX portability. */
363 if (dirent->d_type != DT_DIR
364 || strspn (dirent->d_name, "0123456789") != strlen (dirent->d_name))
366 (*func) (atoi (dirent->d_name), data);
370 perror ("readdir (\"/proc\")");
373 if (closedir (dir) != 0)
375 perror ("closedir (\"/proc\")");
380 static int rip_check (pid_t pid, const char *link)
382 assert (pid != getpid ());
384 return strcmp (link, childptyname) == 0;
392 static struct pid *pid_list;
394 static int pid_found (pid_t pid)
398 for (entry = pid_list; entry != NULL; entry = entry->next)
399 if (entry->pid == pid)
404 static void pid_record (pid_t pid)
411 entry = malloc (sizeof (*entry));
414 fprintf (stderr, "%s: malloc: %m\n", progname);
418 entry->next = pid_list;
422 static void pid_forall (void (*func) (pid_t pid))
426 for (entry = pid_list; entry != NULL; entry = entry->next)
427 (*func) (entry->pid);
430 /* Returns 0 on failure. */
431 static pid_t pid_get_parent (pid_t pid)
438 if (snprintf (fname, sizeof fname, "/proc/%d/status", (int) pid) < 0)
440 perror ("snprintf(3)");
443 f = fopen (fname, "r");
448 while (errno = 0, fgets (line, sizeof line, f) == line)
450 if (strncmp (line, "PPid:\t", sizeof "PPid:\t" - 1) != 0)
452 retval = atoi (line + sizeof "PPid:\t" - 1);
458 fprintf (stderr, "%s: fgets (\"%s\"): %m\n", progname, fname);
463 fprintf (stderr, "%s: fclose (\"%s\"): %m\n", progname, fname);
469 static void killtree (pid_t pid);
471 static void killtree_pid_fs_scan (pid_t pid, void *data)
473 pid_t parent_pid = *(pid_t *) data;
479 if (pid_get_parent (pid) != parent_pid)
485 static void killtree (pid_t pid)
488 pid_fs_scan (killtree_pid_fs_scan, &pid);
491 static void rip_pid_fs_scan (pid_t pid, void *data)
495 /* Shouldn't happen. */
496 if (pid == getpid ())
499 /* Check both PGID and the stale file descriptors. */
500 pgid = getpgid (pid);
502 || fd_fs_scan (pid, rip_check) != 0)
506 static void killproc (pid_t pid)
510 cmdline = read_cmdline (pid);
511 /* Avoid printing the message for already gone processes. */
512 if (kill (pid, 0) != 0 && errno == ESRCH)
516 fprintf (stderr, "%s: Killed -9 orphan PID %d: %s\n", progname, (int) pid, cmdline);
517 if (kill (pid, SIGKILL))
520 fprintf (stderr, "%s: kill (%d, SIGKILL): %m\n", progname, (int) pid);
523 /* Do not waitpid(2) as it cannot be our direct descendant and it gets
524 cleaned up by init(8). */
527 pid_got = waitpid (pid, NULL, 0);
530 fprintf (stderr, "%s: waitpid (%d) != %d: %m\n", progname,
531 (int) pid, (int) pid_got);
539 pid_fs_scan (rip_pid_fs_scan, NULL);
540 pid_forall (killproc);
543 int main (int argc, char **argv)
547 if (argc < 2 || strcmp (argv[1], "-h") == 0
548 || strcmp (argv[1], "--help") == 0)
550 fputs ("Syntax: orphanripper <execvp(3) commandline>\n", stdout);