Blame SOURCES/gdb-orphanripper.c

0a406a
/*
0a406a
 * Copyright 2006-2007 Free Software Foundation, Inc.
0a406a
 *
0a406a
 * This program is free software; you can redistribute it and/or modify
0a406a
 * it under the terms of the GNU General Public License as published by
0a406a
 * the Free Software Foundation; either version 2 of the License, or
0a406a
 * (at your option) any later version.
0a406a
 *
0a406a
 * This program is distributed in the hope that it will be useful,
0a406a
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
0a406a
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
0a406a
 * GNU General Public License for more details.
0a406a
 *
0a406a
 * You should have received a copy of the GNU General Public License
0a406a
 * along with this program; if not, write to the Free Software
0a406a
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
0a406a
 *
0a406a
 * Reap any leftover children possibly holding file descriptors.
0a406a
 * Children are identified by the stale file descriptor or PGID / SID.
0a406a
 * Both can be missed but only the stale file descriptors are important for us.
0a406a
 * PGID / SID may be set by the children on their own.
0a406a
 * If we fine a candidate we kill it will all its process tree (grandchildren).
0a406a
 * The child process is run with `2>&1' redirection (due to forkpty(3)).
0a406a
 * 2007-07-10  Jan Kratochvil  <jan.kratochvil@redhat.com>
0a406a
 */
0a406a
0a406a
/* For getpgid(2).  */
0a406a
#define _GNU_SOURCE 1
0a406a
0a406a
#include <stdio.h>
0a406a
#include <stdlib.h>
0a406a
#include <sys/types.h>
0a406a
#include <sys/wait.h>
0a406a
#include <dirent.h>
0a406a
#include <unistd.h>
0a406a
#include <errno.h>
0a406a
#include <ctype.h>
0a406a
#include <string.h>
0a406a
#include <limits.h>
0a406a
#include <fcntl.h>
0a406a
#include <assert.h>
0a406a
#include <pty.h>
0a406a
#include <poll.h>
0a406a
#include <sys/stat.h>
0a406a
0a406a
#define LENGTH(x) (sizeof (x) / sizeof (*(x)))
0a406a
0a406a
static const char *progname;
0a406a
0a406a
static volatile pid_t child;
0a406a
0a406a
static void signal_chld (int signo)
0a406a
{
0a406a
}
0a406a
0a406a
static volatile int signal_alrm_hit = 0;
0a406a
0a406a
static void signal_alrm (int signo)
0a406a
{
0a406a
  signal_alrm_hit = 1;
0a406a
}
0a406a
0a406a
static char childptyname[LINE_MAX];
0a406a
0a406a
static void print_child_error (const char *reason, char **argv)
0a406a
{
0a406a
  char **sp;
0a406a
0a406a
  fprintf (stderr, "%s: %d %s:", progname, (int) child, reason);
0a406a
  for (sp = argv; *sp != NULL; sp++)
0a406a
    {
0a406a
      fputc (' ', stderr);
0a406a
      fputs (*sp, stderr);
0a406a
    }
0a406a
  fputc ('\n', stderr);
0a406a
}
0a406a
0a406a
static int read_out (int amaster)
0a406a
{
0a406a
  char buf[LINE_MAX];
0a406a
  ssize_t buf_got;
0a406a
0a406a
  buf_got = read (amaster, buf, sizeof buf);
0a406a
  if (buf_got == 0)
0a406a
    return 0;
0a406a
  /* Weird but at least after POLLHUP we get EIO instead of just EOF.  */
0a406a
  if (buf_got == -1 && errno == EIO)
0a406a
    return 0;
0a406a
  if (buf_got == -1 && errno == EAGAIN)
0a406a
    return 0;
0a406a
  if (buf_got < 0)
0a406a
    {
0a406a
      perror ("read (amaster)");
0a406a
      exit (EXIT_FAILURE);
0a406a
    }
0a406a
  if (write (STDOUT_FILENO, buf, buf_got) != buf_got)
0a406a
    {
0a406a
      perror ("write(2)");
0a406a
      exit (EXIT_FAILURE);
0a406a
    }
0a406a
  return 1;
0a406a
}
0a406a
0a406a
/* kill (child, 0) == 0 sometimes even when CHILD's state is already "Z".  */
0a406a
0a406a
static int child_exited (void)
0a406a
{
0a406a
  char buf[200];
0a406a
  int fd, i, retval;
0a406a
  ssize_t got;
0a406a
  char state[3];
0a406a
0a406a
  snprintf (buf, sizeof (buf), "/proc/%ld/stat", (long) child);
0a406a
  fd = open (buf, O_RDONLY);
0a406a
  if (fd == -1)
0a406a
    {
0a406a
      perror ("open (/proc/CHILD/stat)");
0a406a
      exit (EXIT_FAILURE);
0a406a
    }
0a406a
  got = read (fd, buf, sizeof(buf));
0a406a
  if (got <= 0)
0a406a
    {
0a406a
      perror ("read (/proc/CHILD/stat)");
0a406a
      exit (EXIT_FAILURE);
0a406a
    }
0a406a
  if (close (fd) != 0)
0a406a
    {
0a406a
      perror ("close (/proc/CHILD/stat)");
0a406a
      exit (EXIT_FAILURE);
0a406a
    }
0a406a
  /* RHEL-5 does not support %ms.  */
0a406a
  i = sscanf (buf, "%*d%*s%2s", state);
0a406a
  if (i != 1)
0a406a
    {
0a406a
      perror ("sscanf (/proc/CHILD/stat)");
0a406a
      exit (EXIT_FAILURE);
0a406a
    }
0a406a
  retval = strcmp (state, "Z") == 0;
0a406a
  return retval;
0a406a
}
0a406a
0a406a
static int spawn (char **argv, int timeout)
0a406a
{
0a406a
  pid_t child_got;
0a406a
  int status, amaster, i, rc;
0a406a
  struct sigaction act;
0a406a
  sigset_t set;
0a406a
  struct termios termios;
0a406a
  unsigned alarm_orig;
0a406a
0a406a
  /* We do not use signal(2) to be sure we do not have SA_RESTART.  */
0a406a
  memset (&act, 0, sizeof (act));
0a406a
  act.sa_handler = signal_chld;
0a406a
  i = sigemptyset (&act.sa_mask);
0a406a
  assert (i == 0);
0a406a
  act.sa_flags = 0;	/* !SA_RESTART */
0a406a
  i = sigaction (SIGCHLD, &act, NULL);
0a406a
  assert (i == 0);
0a406a
0a406a
  i = sigemptyset (&set);
0a406a
  assert (i == 0);
0a406a
  i = sigaddset (&set, SIGCHLD);
0a406a
  assert (i == 0);
0a406a
  i = sigprocmask (SIG_SETMASK, &set, NULL);
0a406a
  assert (i == 0);
0a406a
0a406a
  /* With TERMP passed as NULL we get "\n" -> "\r\n".  */
0a406a
  termios.c_iflag = IGNBRK | IGNPAR;
0a406a
  termios.c_oflag = 0;
0a406a
  termios.c_cflag = CS8 | CREAD | CLOCAL | HUPCL | B9600;
0a406a
  termios.c_lflag = IEXTEN | NOFLSH;
0a406a
  memset (termios.c_cc, _POSIX_VDISABLE, sizeof (termios.c_cc));
0a406a
  termios.c_cc[VTIME] = 0;
0a406a
  termios.c_cc[VMIN ] = 1;
0a406a
  cfmakeraw (&termios);
0a406a
#ifdef FLUSHO
0a406a
  /* Workaround a readline deadlock bug in _get_tty_settings().  */
0a406a
  termios.c_lflag &= ~FLUSHO;
0a406a
#endif
0a406a
  child = forkpty (&amaster, childptyname, &termios, NULL);
0a406a
  switch (child)
0a406a
    {
0a406a
      case -1:
0a406a
	perror ("forkpty(3)");
0a406a
	exit (EXIT_FAILURE);
0a406a
      case 0:
0a406a
	/* Do not replace STDIN as inferiors query its termios.  */
0a406a
#if 0
0a406a
	i = close (STDIN_FILENO);
0a406a
	assert (i == 0);
0a406a
	i = open ("/dev/null", O_RDONLY);
0a406a
	assert (i == STDIN_FILENO);
0a406a
#endif
0a406a
0a406a
	i = sigemptyset (&set);
0a406a
	assert (i == 0);
0a406a
	i = sigprocmask (SIG_SETMASK, &set, NULL);
0a406a
	assert (i == 0);
0a406a
0a406a
	/* Do not setpgrp(2) in the parent process as the process-group
0a406a
	   is shared for the whole sh(1) pipeline we could be a part
0a406a
	   of.  The process-group is set according to PID of the first
0a406a
	   command in the pipeline.
0a406a
	   We would rip even vi(1) in the case of:
0a406a
		./orphanripper sh -c 'sleep 1&' | vi -
0a406a
	   */
0a406a
	/* Do not setpgrp(2) as our pty would not be ours and we would
0a406a
	   get `SIGSTOP' later, particularly after spawning gdb(1).
0a406a
	   setsid(3) was already executed by forkpty(3) and it would fail if
0a406a
	   executed again.  */
0a406a
	if (getpid() != getpgrp ())
0a406a
	  {
0a406a
	    perror ("getpgrp(2)");
0a406a
	    exit (EXIT_FAILURE);
0a406a
	  }
0a406a
	execvp (argv[0], argv);
0a406a
	perror ("execvp(2)");
0a406a
	exit (EXIT_FAILURE);
0a406a
      default:
0a406a
	break;
0a406a
    }
0a406a
  i = fcntl (amaster, F_SETFL, O_RDWR | O_NONBLOCK);
0a406a
  if (i != 0)
0a406a
    {
0a406a
      perror ("fcntl (amaster, F_SETFL, O_NONBLOCK)");
0a406a
      exit (EXIT_FAILURE);
0a406a
    }
0a406a
0a406a
  /* We do not use signal(2) to be sure we do not have SA_RESTART.  */
0a406a
  act.sa_handler = signal_alrm;
0a406a
  i = sigaction (SIGALRM, &act, NULL);
0a406a
  assert (i == 0);
0a406a
0a406a
  alarm_orig = alarm (timeout);
0a406a
  assert (alarm_orig == 0);
0a406a
0a406a
  i = sigemptyset (&set);
0a406a
  assert (i == 0);
0a406a
0a406a
  while (!signal_alrm_hit)
0a406a
    {
0a406a
      struct pollfd pollfd;
0a406a
0a406a
      pollfd.fd = amaster;
0a406a
      pollfd.events = POLLIN;
0a406a
      i = ppoll (&pollfd, 1, NULL, &set);
0a406a
      if (i == -1 && errno == EINTR)
0a406a
	{
0a406a
	  if (child_exited ())
0a406a
	    break;
0a406a
	  /* Non-CHILD child may have exited.  */
0a406a
	  continue;
0a406a
	}
0a406a
      assert (i == 1);
0a406a
      /* Data available?  Process it first.  */
0a406a
      if (pollfd.revents & POLLIN)
0a406a
	{
0a406a
	  if (!read_out (amaster))
0a406a
	    {
0a406a
	      fprintf (stderr, "%s: Unexpected EOF\n", progname);
0a406a
	      exit (EXIT_FAILURE);
0a406a
	    }
0a406a
	}
0a406a
      if (pollfd.revents & POLLHUP)
0a406a
        break;
0a406a
      if ((pollfd.revents &= ~POLLIN) != 0)
0a406a
	{
0a406a
	  fprintf (stderr, "%s: ppoll(2): revents 0x%x\n", progname,
0a406a
		   (unsigned) pollfd.revents);
0a406a
	  exit (EXIT_FAILURE);
0a406a
	}
0a406a
      /* Child exited?  */
0a406a
      if (child_exited ())
0a406a
	break;
0a406a
    }
0a406a
0a406a
  if (signal_alrm_hit)
0a406a
    {
0a406a
      i = kill (child, SIGKILL);
0a406a
      assert (i == 0);
0a406a
    }
0a406a
  else
0a406a
    alarm (0);
0a406a
0a406a
  /* WNOHANG still could fail.  */
0a406a
  child_got = waitpid (child, &status, 0);
0a406a
  if (child != child_got)
0a406a
    {
0a406a
      fprintf (stderr, "waitpid (%d) = %d: %m\n", (int) child, (int) child_got);
0a406a
      exit (EXIT_FAILURE);
0a406a
    }
0a406a
  if (signal_alrm_hit)
0a406a
    {
0a406a
      char *buf;
0a406a
0a406a
      if (asprintf (&buf, "Timed out after %d seconds", timeout) != -1)
0a406a
	{
0a406a
	  print_child_error (buf, argv);
0a406a
	  free (buf);
0a406a
	}
0a406a
      rc = 128 + SIGALRM;
0a406a
    }
0a406a
  else if (WIFEXITED (status))
0a406a
    rc = WEXITSTATUS (status);
0a406a
  else if (WIFSIGNALED (status))
0a406a
    {
0a406a
      print_child_error (strsignal (WTERMSIG (status)), argv);
0a406a
      rc = 128 + WTERMSIG (status);
0a406a
    }
0a406a
  else if (WIFSTOPPED (status))
0a406a
    {
0a406a
      fprintf (stderr, "waitpid (%d): WIFSTOPPED - WSTOPSIG is %d\n",
0a406a
	       (int) child, WSTOPSIG (status));
0a406a
      exit (EXIT_FAILURE);
0a406a
    }
0a406a
  else
0a406a
    {
0a406a
      fprintf (stderr, "waitpid (%d): !WIFEXITED (%d)\n", (int) child, status);
0a406a
      exit (EXIT_FAILURE);
0a406a
    }
0a406a
0a406a
  /* Not used in fact.  */
0a406a
  i = sigprocmask (SIG_SETMASK, &set, NULL);
0a406a
  assert (i == 0);
0a406a
0a406a
  /* Do not unset O_NONBLOCK as a stale child (the whole purpose of this
0a406a
     program) having open its output pty would block us in read_out.  */
0a406a
#if 0
0a406a
  i = fcntl (amaster, F_SETFL, O_RDONLY /* !O_NONBLOCK */);
0a406a
  if (i != 0)
0a406a
    {
0a406a
      perror ("fcntl (amaster, F_SETFL, O_RDONLY /* !O_NONBLOCK */)");
0a406a
      exit (EXIT_FAILURE);
0a406a
    }
0a406a
#endif
0a406a
0a406a
  while (read_out (amaster));
0a406a
0a406a
  /* Do not close the master FD as the child would have `/dev/pts/23 (deleted)'
0a406a
     entries which are not expected (and expecting ` (deleted)' would be
0a406a
     a race.  */
0a406a
#if 0
0a406a
  i = close (amaster);
0a406a
  if (i != 0)
0a406a
    {
0a406a
      perror ("close (forkpty ()'s amaster)");
0a406a
      exit (EXIT_FAILURE);
0a406a
    }
0a406a
#endif
0a406a
0a406a
  return rc;
0a406a
}
0a406a
0a406a
/* Detected commandline may look weird due to a race:
0a406a
   Original command:
0a406a
	./orphanripper sh -c 'sleep 1&' &
0a406a
   Correct output:
0a406a
	[1] 29610
0a406a
	./orphanripper: Killed -9 orphan PID 29612 (PGID 29611): sleep 1
0a406a
   Raced output (sh(1) child still did not update its argv[]):
0a406a
	[1] 29613
0a406a
	./orphanripper: Killed -9 orphan PID 29615 (PGID 29614): sh -c sleep 1&
0a406a
   We could delay a bit before ripping the children.  */
0a406a
static const char *read_cmdline (pid_t pid)
0a406a
{
0a406a
  char cmdline_fname[32];
0a406a
  static char cmdline[LINE_MAX];
0a406a
  int fd;
0a406a
  ssize_t got;
0a406a
  char *s;
0a406a
0a406a
  if (snprintf (cmdline_fname, sizeof cmdline_fname, "/proc/%d/cmdline",
0a406a
      (int) pid) < 0)
0a406a
    return NULL;
0a406a
  fd = open (cmdline_fname, O_RDONLY);
0a406a
  if (fd == -1)
0a406a
    {
0a406a
      /* It may have already exited - ENOENT.  */
0a406a
#if 0
0a406a
      fprintf (stderr, "%s: open (\"%s\"): %m\n", progname, cmdline_fname);
0a406a
#endif
0a406a
      return NULL;
0a406a
    }
0a406a
  got = read (fd, cmdline, sizeof (cmdline) - 1);
0a406a
  if (got == -1)
0a406a
    fprintf (stderr, "%s: read (\"%s\"): %m\n", progname,
0a406a
       cmdline_fname);
0a406a
  if (close (fd) != 0)
0a406a
    fprintf (stderr, "%s: close (\"%s\"): %m\n", progname,
0a406a
       cmdline_fname);
0a406a
  if (got < 0)
0a406a
    return NULL;
0a406a
  /* Convert '\0' argument delimiters to spaces.  */
0a406a
  for (s = cmdline; s < cmdline + got; s++)
0a406a
    if (!*s)
0a406a
      *s = ' ';
0a406a
  /* Trim the trailing spaces (typically single '\0'->' ').  */
0a406a
  while (s > cmdline && isspace (s[-1]))
0a406a
    s--;
0a406a
  *s = 0;
0a406a
  return cmdline;
0a406a
}
0a406a
0a406a
static int dir_scan (const char *dirname,
0a406a
		  int (*callback) (struct dirent *dirent, const char *pathname))
0a406a
{
0a406a
  DIR *dir;
0a406a
  struct dirent *dirent;
0a406a
  int rc = 0;
0a406a
0a406a
  dir = opendir (dirname);
0a406a
  if (dir == NULL)
0a406a
    {
0a406a
      if (errno == EACCES || errno == ENOENT)
0a406a
	return rc;
0a406a
      fprintf (stderr, "%s: opendir (\"%s\"): %m\n", progname, dirname);
0a406a
      exit (EXIT_FAILURE);
0a406a
    }
0a406a
  while ((errno = 0, dirent = readdir (dir)))
0a406a
    {
0a406a
      char pathname[LINE_MAX];
0a406a
      int pathname_len;
0a406a
0a406a
      pathname_len = snprintf (pathname, sizeof pathname, "%s/%s",
0a406a
				 dirname, dirent->d_name);
0a406a
      if (pathname_len <= 0 || pathname_len >= (int) sizeof pathname)
0a406a
	{
0a406a
	  fprintf (stderr, "entry file name too long: `%s' / `%s'\n",
0a406a
		   dirname, dirent->d_name);
0a406a
	  continue;
0a406a
	}
0a406a
      /* RHEL-4.5 on s390x never fills in D_TYPE.  */
0a406a
      if (dirent->d_type == DT_UNKNOWN)
0a406a
        {
0a406a
	  struct stat statbuf;
0a406a
	  int i;
0a406a
0a406a
	  /* We are not interested in the /proc/PID/fd/ links targets.  */
0a406a
	  i = lstat (pathname, &statbuf);
0a406a
	  if (i == -1)
0a406a
	    {
0a406a
	      if (errno == EACCES || errno == ENOENT)
0a406a
	        continue;
0a406a
	      fprintf (stderr, "%s: stat (\"%s\"): %m\n", progname, pathname);
0a406a
	      exit (EXIT_FAILURE);
0a406a
	    }
0a406a
	  if (S_ISDIR (statbuf.st_mode))
0a406a
	    dirent->d_type = DT_DIR;
0a406a
	  if (S_ISLNK (statbuf.st_mode))
0a406a
	    dirent->d_type = DT_LNK;
0a406a
	  /* No other D_TYPE types used in this code.  */
0a406a
	}
0a406a
      rc = (*callback) (dirent, pathname);
0a406a
      if (rc != 0)
0a406a
	{
0a406a
	  errno = 0;
0a406a
	  break;
0a406a
	}
0a406a
    }
0a406a
  if (errno != 0)
0a406a
    {
0a406a
      fprintf (stderr, "%s: readdir (\"%s\"): %m\n", progname, dirname);
0a406a
      exit (EXIT_FAILURE);
0a406a
    }
0a406a
  if (closedir (dir) != 0)
0a406a
    {
0a406a
      fprintf (stderr, "%s: closedir (\"%s\"): %m\n", progname, dirname);
0a406a
      exit (EXIT_FAILURE);
0a406a
    }
0a406a
  return rc;
0a406a
}
0a406a
0a406a
static int fd_fs_scan (pid_t pid, int (*func) (pid_t pid, const char *link))
0a406a
{
0a406a
  char dirname[64];
0a406a
0a406a
  if (snprintf (dirname, sizeof dirname, "/proc/%d/fd", (int) pid) < 0)
0a406a
    {
0a406a
      perror ("snprintf(3)");
0a406a
      exit (EXIT_FAILURE);
0a406a
    }
0a406a
0a406a
  int callback (struct dirent *dirent, const char *pathname)
0a406a
  {
0a406a
    char buf[LINE_MAX];
0a406a
    ssize_t buf_len;
0a406a
0a406a
    if ((dirent->d_type != DT_DIR && dirent->d_type != DT_LNK)
0a406a
	|| (dirent->d_type == DT_DIR && strcmp (dirent->d_name, ".") != 0
0a406a
	    && strcmp (dirent->d_name, "..") != 0)
0a406a
	|| (dirent->d_type == DT_LNK && strspn (dirent->d_name, "0123456789")
0a406a
	    != strlen (dirent->d_name)))
0a406a
      {
0a406a
	fprintf (stderr, "Unexpected entry \"%s\" (d_type %u)"
0a406a
			 " on readdir (\"%s\"): %m\n",
0a406a
		 dirent->d_name, (unsigned) dirent->d_type, dirname);
0a406a
	return 0;
0a406a
      }
0a406a
    if (dirent->d_type == DT_DIR)
0a406a
      return 0;
0a406a
    buf_len = readlink (pathname, buf, sizeof buf - 1);
0a406a
    if (buf_len <= 0 || buf_len >= (ssize_t) sizeof buf - 1)
0a406a
      {
0a406a
	if (errno != ENOENT && errno != EACCES)
0a406a
	  fprintf (stderr, "Error reading link \"%s\": %m\n", pathname);
0a406a
	return 0;
0a406a
      }
0a406a
    buf[buf_len] = 0;
0a406a
    return (*func) (pid, buf);
0a406a
  }
0a406a
0a406a
  return dir_scan (dirname, callback);
0a406a
}
0a406a
0a406a
static void pid_fs_scan (void (*func) (pid_t pid, void *data), void *data)
0a406a
{
0a406a
  int callback (struct dirent *dirent, const char *pathname)
0a406a
  {
0a406a
    if (dirent->d_type != DT_DIR
0a406a
	|| strspn (dirent->d_name, "0123456789") != strlen (dirent->d_name))
0a406a
      return 0;
0a406a
    (*func) (atoi (dirent->d_name), data);
0a406a
    return 0;
0a406a
  }
0a406a
0a406a
  dir_scan ("/proc", callback);
0a406a
}
0a406a
0a406a
static int rip_check_ptyname (pid_t pid, const char *link)
0a406a
{
0a406a
  assert (pid != getpid ());
0a406a
0a406a
  return strcmp (link, childptyname) == 0;
0a406a
}
0a406a
0a406a
struct pid
0a406a
  {
0a406a
    struct pid *next;
0a406a
    pid_t pid;
0a406a
  };
0a406a
static struct pid *pid_list;
0a406a
0a406a
static int pid_found (pid_t pid)
0a406a
{
0a406a
  struct pid *entry;
0a406a
0a406a
  for (entry = pid_list; entry != NULL; entry = entry->next)
0a406a
    if (entry->pid == pid)
0a406a
      return 1;
0a406a
  return 0;
0a406a
}
0a406a
0a406a
/* Single pass is not enough, a (multithreaded) process was seen to survive.
0a406a
   Repeated killing of the same process is not enough, zombies can be killed.
0a406a
   */
0a406a
static int cleanup_acted;
0a406a
0a406a
static void pid_record (pid_t pid)
0a406a
{
0a406a
  struct pid *entry;
0a406a
0a406a
  if (pid_found (pid))
0a406a
    return;
0a406a
  cleanup_acted = 1;
0a406a
0a406a
  entry = malloc (sizeof (*entry));
0a406a
  if (entry == NULL)
0a406a
    {
0a406a
      fprintf (stderr, "%s: malloc: %m\n", progname);
0a406a
      exit (EXIT_FAILURE);
0a406a
    }
0a406a
  entry->pid = pid;
0a406a
  entry->next = pid_list;
0a406a
  pid_list = entry;
0a406a
}
0a406a
0a406a
static void pid_forall (void (*func) (pid_t pid))
0a406a
{
0a406a
  struct pid *entry;
0a406a
0a406a
  for (entry = pid_list; entry != NULL; entry = entry->next)
0a406a
    (*func) (entry->pid);
0a406a
}
0a406a
0a406a
/* Returns 0 on failure.  */
0a406a
static pid_t pid_get_parent (pid_t pid)
0a406a
{
0a406a
  char fname[64];
0a406a
  FILE *f;
0a406a
  char line[LINE_MAX];
0a406a
  pid_t retval = 0;
0a406a
0a406a
  if (snprintf (fname, sizeof fname, "/proc/%d/status", (int) pid) < 0)
0a406a
    {
0a406a
      perror ("snprintf(3)");
0a406a
      exit (EXIT_FAILURE);
0a406a
    }
0a406a
  f = fopen (fname, "r");
0a406a
  if (f == NULL)
0a406a
    {
0a406a
      return 0;
0a406a
    }
0a406a
  while (errno = 0, fgets (line, sizeof line, f) == line)
0a406a
    {
0a406a
      if (strncmp (line, "PPid:\t", sizeof "PPid:\t" - 1) != 0)
0a406a
	continue;
0a406a
      retval = atoi (line + sizeof "PPid:\t" - 1);
0a406a
      errno = 0;
0a406a
      break;
0a406a
    }
0a406a
  if (errno != 0)
0a406a
    {
0a406a
      fprintf (stderr, "%s: fgets (\"%s\"): %m\n", progname, fname);
0a406a
      exit (EXIT_FAILURE);
0a406a
    }
0a406a
  if (fclose (f) != 0)
0a406a
    {
0a406a
      fprintf (stderr, "%s: fclose (\"%s\"): %m\n", progname, fname);
0a406a
      exit (EXIT_FAILURE);
0a406a
    }
0a406a
  return retval;
0a406a
}
0a406a
0a406a
static void killtree (pid_t pid);
0a406a
0a406a
static void killtree_pid_fs_scan (pid_t pid, void *data)
0a406a
{
0a406a
  pid_t parent_pid = *(pid_t *) data;
0a406a
0a406a
  /* Do not optimize it as we could miss some newly spawned processes.
0a406a
     Always traverse all the leaves.  */
0a406a
#if 0
0a406a
  /* Optimization.  */
0a406a
  if (pid_found (pid))
0a406a
    return;
0a406a
#endif
0a406a
0a406a
  if (pid_get_parent (pid) != parent_pid)
0a406a
    return;
0a406a
0a406a
  killtree (pid);
0a406a
}
0a406a
0a406a
static void killtree (pid_t pid)
0a406a
{
0a406a
  pid_record (pid);
0a406a
  pid_fs_scan (killtree_pid_fs_scan, &pid;;
0a406a
}
0a406a
0a406a
static void rip_pid_fs_scan (pid_t pid, void *data)
0a406a
{
0a406a
  pid_t pgid;
0a406a
0a406a
  /* Shouldn't happen.  */
0a406a
  if (pid == getpid ())
0a406a
    return;
0a406a
0a406a
  /* Check both PGID and the stale file descriptors.  */
0a406a
  pgid = getpgid (pid);
0a406a
  if (pgid == child
0a406a
      || fd_fs_scan (pid, rip_check_ptyname) != 0)
0a406a
    killtree (pid);
0a406a
}
0a406a
0a406a
static void killproc (pid_t pid)
0a406a
{
0a406a
  const char *cmdline;
0a406a
0a406a
  cmdline = read_cmdline (pid);
0a406a
  /* Avoid printing the message for already gone processes.  */
0a406a
  if (kill (pid, 0) != 0 && errno == ESRCH)
0a406a
    return;
0a406a
  if (cmdline == NULL)
0a406a
    cmdline = "<error>";
0a406a
  fprintf (stderr, "%s: Killed -9 orphan PID %d: %s\n", progname, (int) pid, cmdline);
0a406a
  if (kill (pid, SIGKILL) == 0)
0a406a
    cleanup_acted = 1;
0a406a
  else if (errno != ESRCH)
0a406a
    fprintf (stderr, "%s: kill (%d, SIGKILL): %m\n", progname, (int) pid);
0a406a
  /* RHEL-3 kernels cannot SIGKILL a `T (stopped)' process.  */
0a406a
  kill (pid, SIGCONT);
0a406a
  /* Do not waitpid(2) as it cannot be our direct descendant and it gets
0a406a
     cleaned up by init(8).  */
0a406a
#if 0
0a406a
  pid_t pid_got;
0a406a
  pid_got = waitpid (pid, NULL, 0);
0a406a
  if (pid != pid_got)
0a406a
    {
0a406a
      fprintf (stderr, "%s: waitpid (%d) != %d: %m\n", progname,
0a406a
	 (int) pid, (int) pid_got);
0a406a
      return;
0a406a
    }
0a406a
#endif
0a406a
}
0a406a
0a406a
static void rip (void)
0a406a
{
0a406a
  cleanup_acted = 0;
0a406a
  do
0a406a
    {
0a406a
      if (cleanup_acted)
0a406a
        usleep (1000000 / 10);
0a406a
      cleanup_acted = 0;
0a406a
      pid_fs_scan (rip_pid_fs_scan, NULL);
0a406a
      pid_forall (killproc);
0a406a
    }
0a406a
  while (cleanup_acted);
0a406a
}
0a406a
0a406a
int main (int argc, char **argv)
0a406a
{
0a406a
  int timeout = 0;
0a406a
  int rc;
0a406a
0a406a
  progname = *argv++;
0a406a
  argc--;
0a406a
0a406a
  if (argc < 1 || strcmp (*argv, "-h") == 0
0a406a
      || strcmp (*argv, "--help") == 0)
0a406a
    {
0a406a
      puts ("Syntax: orphanripper [-t <seconds>] <execvp(3) commandline>");
0a406a
      exit (EXIT_FAILURE);
0a406a
    }
0a406a
  if ((*argv)[0] == '-' && (*argv)[1] == 't')
0a406a
    {
0a406a
      char *timeout_s = NULL;
0a406a
0a406a
      if ((*argv)[2] == 0)
0a406a
	timeout_s = *++argv;
0a406a
      else if (isdigit ((*argv)[2]))
0a406a
	timeout_s = (*argv) + 2;
0a406a
      if (timeout_s != NULL)
0a406a
	{
0a406a
	  long l;
0a406a
	  char *endptr;
0a406a
0a406a
	  argv++;
0a406a
	  l = strtol (timeout_s, &endptr, 0);
0a406a
	  timeout = l;
0a406a
	  if ((endptr != NULL && *endptr != 0) || timeout < 0 || timeout != l)
0a406a
	    {
0a406a
	      fprintf (stderr, "%s: Invalid timeout value: %s\n", progname,
0a406a
		       timeout_s);
0a406a
	      exit (EXIT_FAILURE);
0a406a
	    }
0a406a
	}
0a406a
    }
0a406a
0a406a
  rc = spawn (argv, timeout);
0a406a
  rip ();
0a406a
  return rc;
0a406a
}