Blame SOURCES/gdb-orphanripper.c

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