Blame SOURCES/gdb-orphanripper.c

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