Blame SOURCES/gdb-orphanripper.c

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