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>
31 #include <sys/types.h>
44 static const char *progname;
46 static volatile int signal_child_hit = 0;
48 static void signal_child (int signo)
53 static char childptyname[LINE_MAX];
56 static int spawn (char **argv)
59 int status, amaster, i;
63 /* Never miss SIGCHLD. */
64 i = sigemptyset (&sigset);
66 i = sigaddset (&sigset, SIGCHLD);
68 i = sigprocmask (SIG_BLOCK, &sigset, NULL);
70 i = sigemptyset (&sigset);
73 /* We do not use signal(2) to be sure we have SA_RESTART unset. */
74 memset (&act, 0, sizeof (act));
75 act.sa_handler = signal_child;
76 i = sigemptyset (&act.sa_mask);
79 i = sigaction (SIGCHLD, &act, NULL);
82 child = forkpty (&amaster, childptyname, NULL, NULL);
86 perror ("forkpty(3)");
89 /* Do not setpgrp(2) in the parent process as the process-group
90 is shared for the whole sh(1) pipeline we could be a part
91 of. The process-group is set according to PID of the first
92 command in the pipeline.
93 We would rip even vi(1) in the case of:
94 ./orphanripper sh -c 'sleep 1&' | vi -
96 /* Do not setpgrp(2) as our pty would not be ours and we would
97 get `SIGSTOP' later, particularly after spawning gdb(1).
98 setsid(3) was already executed by forkpty(3) and it would fail if
100 if (getpid() != getpgrp ())
102 perror ("getpgrp(2)");
105 execvp (argv[1], argv + 1);
106 perror ("execvp(2)");
111 i = fcntl (amaster, F_SETFL, O_RDWR | O_NONBLOCK);
114 perror ("fcntl (amaster, F_SETFL, O_NONBLOCK)");
119 struct pollfd pollfd;
124 pollfd.events = POLLIN;
125 i = ppoll (&pollfd, 1, NULL, &sigset);
126 assert (i == -1 || i == 1);
129 assert (errno == EINTR && signal_child_hit != 0);
133 assert (pollfd.revents != 0);
134 if (pollfd.revents & POLLHUP)
136 if (pollfd.revents != POLLIN)
138 fprintf (stderr, "%s: ppoll(2): revents 0x%x\n", progname,
139 (unsigned) pollfd.revents);
142 buf_got = read (amaster, buf, sizeof buf);
147 perror ("read (amaster)");
150 if (write (STDOUT_FILENO, buf, buf_got) != buf_got)
156 /* WNOHANG still could fail. */
157 child_got = waitpid (child, &status, 0);
158 if (child != child_got)
160 fprintf (stderr, "waitpid (%d) = %d: %m\n", (int) child, (int) child_got);
163 if (!WIFEXITED (status))
165 fprintf (stderr, "waitpid (%d): !WIFEXITED (%d)\n", (int) child, status);
168 /* Do not close the master FD as the child would have `/dev/pts/23 (deleted)'
169 entries which are not expected (and expecting ` (deleted)' would be
175 perror ("close (forkpty ()'s amaster)");
180 return WEXITSTATUS (status);
183 /* Detected commandline may look weird due to a race:
185 ./orphanripper sh -c 'sleep 1&' &
188 ./orphanripper: Killed -9 orphan PID 29612 (PGID 29611): sleep 1
189 Raced output (sh(1) child still did not update its argv[]):
191 ./orphanripper: Killed -9 orphan PID 29615 (PGID 29614): sh -c sleep 1&
192 We could delay a bit before ripping the children. */
193 static const char *read_cmdline (pid_t pid)
195 char cmdline_fname[32];
196 static char cmdline[LINE_MAX];
201 if (snprintf (cmdline_fname, sizeof cmdline_fname, "/proc/%d/cmdline",
204 fd = open (cmdline_fname, O_RDONLY);
207 /* It may have already exited - ENOENT. */
209 fprintf (stderr, "%s: open (\"%s\"): %m\n", progname, cmdline_fname);
213 got = read (fd, cmdline, sizeof (cmdline) - 1);
215 fprintf (stderr, "%s: read (\"%s\"): %m\n", progname,
218 fprintf (stderr, "%s: close (\"%s\"): %m\n", progname,
222 /* Convert '\0' argument delimiters to spaces. */
223 for (s = cmdline; s < cmdline + got; s++)
226 /* Trim the trailing spaces (typically single '\0'->' '). */
227 while (s > cmdline && isspace (s[-1]))
233 static int fd_fs_scan (pid_t pid, int (*func) (pid_t pid, const char *link))
236 struct dirent *dirent;
240 if (snprintf (dirname, sizeof dirname, "/proc/%d/fd", (int) pid) < 0)
242 perror ("snprintf(3)");
245 dir = opendir (dirname);
248 if (errno == EACCES || errno == ENOENT)
250 fprintf (stderr, "%s: opendir (\"%s\"): %m\n", progname, dirname);
253 while ((errno = 0, dirent = readdir (dir)))
255 char linkname[LINE_MAX], buf[LINE_MAX];
259 /* FIXME: POSIX portability. */
260 if ((dirent->d_type != DT_DIR && dirent->d_type != DT_LNK)
261 || (dirent->d_type == DT_DIR && strcmp (dirent->d_name, ".") != 0
262 && strcmp (dirent->d_name, "..") != 0)
263 || (dirent->d_type == DT_LNK && strspn (dirent->d_name, "0123456789")
264 != strlen (dirent->d_name)))
266 /* There is a race, D_TYPE may be uninitialized if stat(2) fails. */
267 if (dirent->d_type != DT_UNKNOWN)
268 fprintf (stderr, "Unexpected entry \"%s\" (d_type %u)"
269 " on readdir (\"%s\"): %m\n",
270 dirent->d_name, (unsigned) dirent->d_type, dirname);
273 if (dirent->d_type == DT_DIR)
275 linkname_len = snprintf (linkname, sizeof linkname, "%s/%s", dirname,
277 if (linkname_len <= 0 || linkname_len >= sizeof linkname)
279 fprintf (stderr, "Link content too long: `%s' / `%s'\n",
280 dirent->d_name, dirent->d_name);
283 buf_len = readlink (linkname, buf, sizeof buf - 1);
284 if (buf_len <= 0 || buf_len >= sizeof buf - 1)
286 if (errno != ENOENT && errno != EACCES)
287 fprintf (stderr, "Error reading link \"%s\": %m\n",
292 rc = (*func) (pid, buf);
301 fprintf (stderr, "%s: readdir (\"%s\"): %m\n", progname, dirname);
304 if (closedir (dir) != 0)
306 fprintf (stderr, "%s: closedir (\"%s\"): %m\n", progname, dirname);
312 static void pid_fs_scan (void (*func) (pid_t pid, void *data), void *data)
315 struct dirent *dirent;
317 dir = opendir ("/proc");
320 perror ("opendir (\"/proc\")");
323 while ((errno = 0, dirent = readdir (dir)))
325 /* FIXME: POSIX portability. */
326 if (dirent->d_type != DT_DIR
327 || strspn (dirent->d_name, "0123456789") != strlen (dirent->d_name))
329 (*func) (atoi (dirent->d_name), data);
333 perror ("readdir (\"/proc\")");
336 if (closedir (dir) != 0)
338 perror ("closedir (\"/proc\")");
343 static int rip_check (pid_t pid, const char *link)
345 assert (pid != getpid ());
347 return strcmp (link, childptyname) == 0;
355 static struct pid *pid_list;
357 static int pid_found (pid_t pid)
361 for (entry = pid_list; entry != NULL; entry = entry->next)
362 if (entry->pid == pid)
367 static void pid_record (pid_t pid)
374 entry = malloc (sizeof (*entry));
377 fprintf (stderr, "%s: malloc: %m\n", progname);
381 entry->next = pid_list;
385 static void pid_forall (void (*func) (pid_t pid))
389 for (entry = pid_list; entry != NULL; entry = entry->next)
390 (*func) (entry->pid);
393 /* Returns 0 on failure. */
394 static pid_t pid_get_parent (pid_t pid)
401 if (snprintf (fname, sizeof fname, "/proc/%d/status", (int) pid) < 0)
403 perror ("snprintf(3)");
406 f = fopen (fname, "r");
411 while (errno = 0, fgets (line, sizeof line, f) == line)
413 if (strncmp (line, "PPid:\t", sizeof "PPid:\t" - 1) != 0)
415 retval = atoi (line + sizeof "PPid:\t" - 1);
421 fprintf (stderr, "%s: fgets (\"%s\"): %m\n", progname, fname);
426 fprintf (stderr, "%s: fclose (\"%s\"): %m\n", progname, fname);
432 static void killtree (pid_t pid);
434 static void killtree_pid_fs_scan (pid_t pid, void *data)
436 pid_t parent_pid = *(pid_t *) data;
442 if (pid_get_parent (pid) != parent_pid)
448 static void killtree (pid_t pid)
451 pid_fs_scan (killtree_pid_fs_scan, &pid);
454 static void rip_pid_fs_scan (pid_t pid, void *data)
458 /* Shouldn't happen. */
459 if (pid == getpid ())
462 /* Check both PGID and the stale file descriptors. */
463 pgid = getpgid (pid);
465 || fd_fs_scan (pid, rip_check) != 0)
469 static void killproc (pid_t pid)
473 cmdline = read_cmdline (pid);
474 /* Avoid printing the message for already gone processes. */
475 if (kill (pid, 0) != 0 && errno == ESRCH)
479 fprintf (stderr, "%s: Killed -9 orphan PID %d: %s\n", progname, (int) pid, cmdline);
480 if (kill (pid, SIGKILL))
483 fprintf (stderr, "%s: kill (%d, SIGKILL): %m\n", progname, (int) pid);
486 /* Do not waitpid(2) as it cannot be our direct descendant and it gets
487 cleaned up by init(8). */
490 pid_got = waitpid (pid, NULL, 0);
493 fprintf (stderr, "%s: waitpid (%d) != %d: %m\n", progname,
494 (int) pid, (int) pid_got);
502 pid_fs_scan (rip_pid_fs_scan, NULL);
503 pid_forall (killproc);
506 int main (int argc, char **argv)
510 if (argc < 2 || strcmp (argv[1], "-h") == 0
511 || strcmp (argv[1], "--help") == 0)
513 fputs ("Syntax: orphanripper <execvp(3) commandline>\n", stdout);