Blame SOURCES/gdb-orphanripper.c

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