Blame SOURCES/gdb-orphanripper.c

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