Blame gettext-tools/gnulib-lib/pipe2-safer.c

Packit 5b56b6
/* Invoke pipe2, but avoid some glitches.
Packit 5b56b6
   Copyright (C) 2005-2006, 2009-2015 Free Software Foundation, Inc.
Packit 5b56b6
Packit 5b56b6
   This program is free software: you can redistribute it and/or modify
Packit 5b56b6
   it under the terms of the GNU General Public License as published by
Packit 5b56b6
   the Free Software Foundation; either version 3 of the License, or
Packit 5b56b6
   (at your option) any later version.
Packit 5b56b6
Packit 5b56b6
   This program is distributed in the hope that it will be useful,
Packit 5b56b6
   but WITHOUT ANY WARRANTY; without even the implied warranty of
Packit 5b56b6
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
Packit 5b56b6
   GNU General Public License for more details.
Packit 5b56b6
Packit 5b56b6
   You should have received a copy of the GNU General Public License
Packit 5b56b6
   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
Packit 5b56b6
Packit 5b56b6
/* Written by Eric Blake.  */
Packit 5b56b6
Packit 5b56b6
#include <config.h>
Packit 5b56b6
Packit 5b56b6
/* Specification.  */
Packit 5b56b6
#include "unistd-safer.h"
Packit 5b56b6
Packit 5b56b6
#include <unistd.h>
Packit 5b56b6
#include <errno.h>
Packit 5b56b6
Packit 5b56b6
/* Like pipe2, but ensure that neither of the file descriptors is
Packit 5b56b6
   STDIN_FILENO, STDOUT_FILENO, or STDERR_FILENO.  */
Packit 5b56b6
Packit 5b56b6
int
Packit 5b56b6
pipe2_safer (int fd[2], int flags)
Packit 5b56b6
{
Packit 5b56b6
  /* This is a generalization of the pipe_safer implementation.  */
Packit 5b56b6
  if (pipe2 (fd, flags) == 0)
Packit 5b56b6
    {
Packit 5b56b6
      int i;
Packit 5b56b6
      for (i = 0; i < 2; i++)
Packit 5b56b6
        {
Packit 5b56b6
          fd[i] = fd_safer_flag (fd[i], flags);
Packit 5b56b6
          if (fd[i] < 0)
Packit 5b56b6
            {
Packit 5b56b6
              int e = errno;
Packit 5b56b6
              close (fd[1 - i]);
Packit 5b56b6
              errno = e;
Packit 5b56b6
              return -1;
Packit 5b56b6
            }
Packit 5b56b6
        }
Packit 5b56b6
Packit 5b56b6
      return 0;
Packit 5b56b6
    }
Packit 5b56b6
  return -1;
Packit 5b56b6
}