Blame SOURCES/gdb-orphanripper.c

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