Blame SOURCES/gdb-orphanripper.c

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