xref: /dflybsd-src/contrib/grep/lib/pipe-safer.c (revision 91b9ed38d3db6a8a8ac5b66da1d43e6e331e259a)
1cf28ed85SJohn Marino /* Invoke pipe, but avoid some glitches.
2*09d4459fSDaniel Fojt    Copyright (C) 2005-2006, 2009-2020 Free Software Foundation, Inc.
3cf28ed85SJohn Marino 
4cf28ed85SJohn Marino    This program is free software: you can redistribute it and/or modify
5cf28ed85SJohn Marino    it under the terms of the GNU General Public License as published by
6cf28ed85SJohn Marino    the Free Software Foundation; either version 3 of the License, or
7cf28ed85SJohn Marino    (at your option) any later version.
8cf28ed85SJohn Marino 
9cf28ed85SJohn Marino    This program is distributed in the hope that it will be useful,
10cf28ed85SJohn Marino    but WITHOUT ANY WARRANTY; without even the implied warranty of
11cf28ed85SJohn Marino    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12cf28ed85SJohn Marino    GNU General Public License for more details.
13cf28ed85SJohn Marino 
14cf28ed85SJohn Marino    You should have received a copy of the GNU General Public License
15*09d4459fSDaniel Fojt    along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
16cf28ed85SJohn Marino 
17cf28ed85SJohn Marino /* Written by Jim Meyering.  */
18cf28ed85SJohn Marino 
19cf28ed85SJohn Marino #include <config.h>
20cf28ed85SJohn Marino 
21cf28ed85SJohn Marino #include "unistd-safer.h"
22cf28ed85SJohn Marino 
23cf28ed85SJohn Marino #include <unistd.h>
24cf28ed85SJohn Marino #include <errno.h>
25cf28ed85SJohn Marino 
26cf28ed85SJohn Marino /* Like pipe, but ensure that neither of the file descriptors is
27cf28ed85SJohn Marino    STDIN_FILENO, STDOUT_FILENO, or STDERR_FILENO.  Fail with ENOSYS on
28cf28ed85SJohn Marino    platforms that lack pipe.  */
29cf28ed85SJohn Marino 
30cf28ed85SJohn Marino int
pipe_safer(int fd[2])31cf28ed85SJohn Marino pipe_safer (int fd[2])
32cf28ed85SJohn Marino {
33cf28ed85SJohn Marino #if HAVE_PIPE
34cf28ed85SJohn Marino   if (pipe (fd) == 0)
35cf28ed85SJohn Marino     {
36cf28ed85SJohn Marino       int i;
37cf28ed85SJohn Marino       for (i = 0; i < 2; i++)
38cf28ed85SJohn Marino         {
39cf28ed85SJohn Marino           fd[i] = fd_safer (fd[i]);
40cf28ed85SJohn Marino           if (fd[i] < 0)
41cf28ed85SJohn Marino             {
42cf28ed85SJohn Marino               int e = errno;
43cf28ed85SJohn Marino               close (fd[1 - i]);
44cf28ed85SJohn Marino               errno = e;
45cf28ed85SJohn Marino               return -1;
46cf28ed85SJohn Marino             }
47cf28ed85SJohn Marino         }
48cf28ed85SJohn Marino 
49cf28ed85SJohn Marino       return 0;
50cf28ed85SJohn Marino     }
51cf28ed85SJohn Marino #else
52cf28ed85SJohn Marino   errno = ENOSYS;
53cf28ed85SJohn Marino #endif
54cf28ed85SJohn Marino 
55cf28ed85SJohn Marino   return -1;
56cf28ed85SJohn Marino }
57