Blame SOURCES/gdb-orphanripper.c

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