Blame SOURCES/gdb-orphanripper.c

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