Blame SOURCES/gdb-orphanripper.c

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