Blame SOURCES/gdb-orphanripper.c

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