Blame SOURCES/gdb-orphanripper.c

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