Blame SOURCES/gdb-orphanripper.c

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