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". */
90 child = forkpty (&amaster, childptyname, &termios, NULL);
94 perror ("forkpty(3)");
97 i = close (pipefd[0]);
99 i = close (pipefd[1]);
101 /* Do not setpgrp(2) in the parent process as the process-group
102 is shared for the whole sh(1) pipeline we could be a part
103 of. The process-group is set according to PID of the first
104 command in the pipeline.
105 We would rip even vi(1) in the case of:
106 ./orphanripper sh -c 'sleep 1&' | vi -
108 /* Do not setpgrp(2) as our pty would not be ours and we would
109 get `SIGSTOP' later, particularly after spawning gdb(1).
110 setsid(3) was already executed by forkpty(3) and it would fail if
112 if (getpid() != getpgrp ())
114 perror ("getpgrp(2)");
117 execvp (argv[1], argv + 1);
118 perror ("execvp(2)");
123 i = fcntl (amaster, F_SETFL, O_RDWR | O_NONBLOCK);
126 perror ("fcntl (amaster, F_SETFL, O_NONBLOCK)");
131 struct pollfd pollfd[2];
135 pollfd[0].fd = amaster;
136 pollfd[0].events = POLLIN;
137 pollfd[1].fd = pipefd[0];
138 pollfd[1].events = POLLIN;
139 i = poll (pollfd, LENGTH (pollfd), -1);
140 if (i == -1 && errno == EINTR)
142 /* Weird but SA_RESTART sometimes does not work. */
146 /* Data available? Process it first. */
147 if (pollfd[0].revents & POLLIN)
149 buf_got = read (amaster, buf, sizeof buf);
152 perror ("read (amaster)");
155 if (write (STDOUT_FILENO, buf, buf_got) != buf_got)
161 if (pollfd[0].revents & POLLHUP)
163 if ((pollfd[0].revents &= ~POLLIN) != 0)
165 fprintf (stderr, "%s: ppoll(2): revents 0x%x\n", progname,
166 (unsigned) pollfd[0].revents);
170 if (pollfd[1].revents & POLLHUP)
172 assert (pollfd[1].revents == 0);
174 /* WNOHANG still could fail. */
175 child_got = waitpid (child, &status, 0);
176 if (child != child_got)
178 fprintf (stderr, "waitpid (%d) = %d: %m\n", (int) child, (int) child_got);
181 if (!WIFEXITED (status))
183 fprintf (stderr, "waitpid (%d): !WIFEXITED (%d)\n", (int) child, status);
187 assert (signal_child_hit != 0);
188 assert (pipefd[1] == -1);
189 i = close (pipefd[0]);
192 /* Do not close the master FD as the child would have `/dev/pts/23 (deleted)'
193 entries which are not expected (and expecting ` (deleted)' would be
199 perror ("close (forkpty ()'s amaster)");
204 return WEXITSTATUS (status);
207 /* Detected commandline may look weird due to a race:
209 ./orphanripper sh -c 'sleep 1&' &
212 ./orphanripper: Killed -9 orphan PID 29612 (PGID 29611): sleep 1
213 Raced output (sh(1) child still did not update its argv[]):
215 ./orphanripper: Killed -9 orphan PID 29615 (PGID 29614): sh -c sleep 1&
216 We could delay a bit before ripping the children. */
217 static const char *read_cmdline (pid_t pid)
219 char cmdline_fname[32];
220 static char cmdline[LINE_MAX];
225 if (snprintf (cmdline_fname, sizeof cmdline_fname, "/proc/%d/cmdline",
228 fd = open (cmdline_fname, O_RDONLY);
231 /* It may have already exited - ENOENT. */
233 fprintf (stderr, "%s: open (\"%s\"): %m\n", progname, cmdline_fname);
237 got = read (fd, cmdline, sizeof (cmdline) - 1);
239 fprintf (stderr, "%s: read (\"%s\"): %m\n", progname,
242 fprintf (stderr, "%s: close (\"%s\"): %m\n", progname,
246 /* Convert '\0' argument delimiters to spaces. */
247 for (s = cmdline; s < cmdline + got; s++)
250 /* Trim the trailing spaces (typically single '\0'->' '). */
251 while (s > cmdline && isspace (s[-1]))
257 static int fd_fs_scan (pid_t pid, int (*func) (pid_t pid, const char *link))
260 struct dirent *dirent;
264 if (snprintf (dirname, sizeof dirname, "/proc/%d/fd", (int) pid) < 0)
266 perror ("snprintf(3)");
269 dir = opendir (dirname);
272 if (errno == EACCES || errno == ENOENT)
274 fprintf (stderr, "%s: opendir (\"%s\"): %m\n", progname, dirname);
277 while ((errno = 0, dirent = readdir (dir)))
279 char linkname[LINE_MAX], buf[LINE_MAX];
283 /* FIXME: POSIX portability. */
284 if ((dirent->d_type != DT_DIR && dirent->d_type != DT_LNK)
285 || (dirent->d_type == DT_DIR && strcmp (dirent->d_name, ".") != 0
286 && strcmp (dirent->d_name, "..") != 0)
287 || (dirent->d_type == DT_LNK && strspn (dirent->d_name, "0123456789")
288 != strlen (dirent->d_name)))
290 /* There is a race, D_TYPE may be uninitialized if stat(2) fails. */
291 if (dirent->d_type != DT_UNKNOWN)
292 fprintf (stderr, "Unexpected entry \"%s\" (d_type %u)"
293 " on readdir (\"%s\"): %m\n",
294 dirent->d_name, (unsigned) dirent->d_type, dirname);
297 if (dirent->d_type == DT_DIR)
299 linkname_len = snprintf (linkname, sizeof linkname, "%s/%s", dirname,
301 if (linkname_len <= 0 || linkname_len >= sizeof linkname)
303 fprintf (stderr, "Link content too long: `%s' / `%s'\n",
304 dirent->d_name, dirent->d_name);
307 buf_len = readlink (linkname, buf, sizeof buf - 1);
308 if (buf_len <= 0 || buf_len >= sizeof buf - 1)
310 if (errno != ENOENT && errno != EACCES)
311 fprintf (stderr, "Error reading link \"%s\": %m\n",
316 rc = (*func) (pid, buf);
325 fprintf (stderr, "%s: readdir (\"%s\"): %m\n", progname, dirname);
328 if (closedir (dir) != 0)
330 fprintf (stderr, "%s: closedir (\"%s\"): %m\n", progname, dirname);
336 static void pid_fs_scan (void (*func) (pid_t pid, void *data), void *data)
339 struct dirent *dirent;
341 dir = opendir ("/proc");
344 perror ("opendir (\"/proc\")");
347 while ((errno = 0, dirent = readdir (dir)))
349 /* FIXME: POSIX portability. */
350 if (dirent->d_type != DT_DIR
351 || strspn (dirent->d_name, "0123456789") != strlen (dirent->d_name))
353 (*func) (atoi (dirent->d_name), data);
357 perror ("readdir (\"/proc\")");
360 if (closedir (dir) != 0)
362 perror ("closedir (\"/proc\")");
367 static int rip_check (pid_t pid, const char *link)
369 assert (pid != getpid ());
371 return strcmp (link, childptyname) == 0;
379 static struct pid *pid_list;
381 static int pid_found (pid_t pid)
385 for (entry = pid_list; entry != NULL; entry = entry->next)
386 if (entry->pid == pid)
391 static void pid_record (pid_t pid)
398 entry = malloc (sizeof (*entry));
401 fprintf (stderr, "%s: malloc: %m\n", progname);
405 entry->next = pid_list;
409 static void pid_forall (void (*func) (pid_t pid))
413 for (entry = pid_list; entry != NULL; entry = entry->next)
414 (*func) (entry->pid);
417 /* Returns 0 on failure. */
418 static pid_t pid_get_parent (pid_t pid)
425 if (snprintf (fname, sizeof fname, "/proc/%d/status", (int) pid) < 0)
427 perror ("snprintf(3)");
430 f = fopen (fname, "r");
435 while (errno = 0, fgets (line, sizeof line, f) == line)
437 if (strncmp (line, "PPid:\t", sizeof "PPid:\t" - 1) != 0)
439 retval = atoi (line + sizeof "PPid:\t" - 1);
445 fprintf (stderr, "%s: fgets (\"%s\"): %m\n", progname, fname);
450 fprintf (stderr, "%s: fclose (\"%s\"): %m\n", progname, fname);
456 static void killtree (pid_t pid);
458 static void killtree_pid_fs_scan (pid_t pid, void *data)
460 pid_t parent_pid = *(pid_t *) data;
466 if (pid_get_parent (pid) != parent_pid)
472 static void killtree (pid_t pid)
475 pid_fs_scan (killtree_pid_fs_scan, &pid);
478 static void rip_pid_fs_scan (pid_t pid, void *data)
482 /* Shouldn't happen. */
483 if (pid == getpid ())
486 /* Check both PGID and the stale file descriptors. */
487 pgid = getpgid (pid);
489 || fd_fs_scan (pid, rip_check) != 0)
493 static void killproc (pid_t pid)
497 cmdline = read_cmdline (pid);
498 /* Avoid printing the message for already gone processes. */
499 if (kill (pid, 0) != 0 && errno == ESRCH)
503 fprintf (stderr, "%s: Killed -9 orphan PID %d: %s\n", progname, (int) pid, cmdline);
504 if (kill (pid, SIGKILL))
507 fprintf (stderr, "%s: kill (%d, SIGKILL): %m\n", progname, (int) pid);
510 /* Do not waitpid(2) as it cannot be our direct descendant and it gets
511 cleaned up by init(8). */
514 pid_got = waitpid (pid, NULL, 0);
517 fprintf (stderr, "%s: waitpid (%d) != %d: %m\n", progname,
518 (int) pid, (int) pid_got);
526 pid_fs_scan (rip_pid_fs_scan, NULL);
527 pid_forall (killproc);
530 int main (int argc, char **argv)
534 if (argc < 2 || strcmp (argv[1], "-h") == 0
535 || strcmp (argv[1], "--help") == 0)
537 fputs ("Syntax: orphanripper <execvp(3) commandline>\n", stdout);