pipe-safer.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /* Invoke pipe, but avoid some glitches.
  2. Copyright (C) 2005, 2006 Free Software Foundation, Inc.
  3. This program is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 2, or (at your option)
  6. any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; if not, write to the Free Software Foundation,
  13. Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
  14. /* Written by Jim Meyering. */
  15. #include <config.h>
  16. #include "unistd-safer.h"
  17. #include <unistd.h>
  18. #include <errno.h>
  19. /* Like pipe, but ensure that neither of the file descriptors is
  20. STDIN_FILENO, STDOUT_FILENO, or STDERR_FILENO. Fail with ENOSYS on
  21. platforms that lack pipe. */
  22. int
  23. pipe_safer (int fd[2])
  24. {
  25. #if HAVE_PIPE
  26. if (pipe (fd) == 0)
  27. {
  28. int i;
  29. for (i = 0; i < 2; i++)
  30. {
  31. fd[i] = fd_safer (fd[i]);
  32. if (fd[i] < 0)
  33. {
  34. int e = errno;
  35. close (fd[1 - i]);
  36. errno = e;
  37. return -1;
  38. }
  39. }
  40. return 0;
  41. }
  42. #else
  43. errno = ENOSYS;
  44. #endif
  45. return -1;
  46. }