Blame SOURCES/gdb-orphanripper.c

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