1 /* Test whether a file descriptor is a pipe.
3 Copyright (C) 2006, 2008-2020 Free Software Foundation, Inc.
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <https://www.gnu.org/licenses/>. */
18 /* Written by Paul Eggert. */
26 #if defined _WIN32 && ! defined __CYGWIN__
27 /* Windows platforms. */
29 /* Get GetFileType. */
32 /* Get _get_osfhandle. */
33 # if GNULIB_MSVC_NOTHROW
34 # include "msvc-nothrow.h"
42 HANDLE h
= (HANDLE
) _get_osfhandle (fd
);
44 if (h
== INVALID_HANDLE_VALUE
)
50 return (GetFileType (h
) == FILE_TYPE_PIPE
);
57 # include <sys/types.h>
58 # include <sys/stat.h>
61 /* The maximum link count for pipes; (nlink_t) -1 if not known. */
62 # ifndef PIPE_LINK_COUNT_MAX
63 # define PIPE_LINK_COUNT_MAX ((nlink_t) (-1))
66 /* Return 1 if FD is a pipe, 0 if not, -1 (setting errno) on error.
68 Test fairly strictly whether FD is a pipe. lseek and checking for
69 ESPIPE does not suffice, since many non-pipe files cause lseek to
70 fail with errno == ESPIPE. */
75 nlink_t pipe_link_count_max
= PIPE_LINK_COUNT_MAX
;
76 bool check_for_fifo
= (HAVE_FIFO_PIPES
== 1);
78 int fstat_result
= fstat (fd
, &st
);
80 if (fstat_result
!= 0)
83 /* We want something that succeeds only for pipes, but on
84 POSIX-conforming hosts S_ISFIFO succeeds for both FIFOs and pipes
85 and we know of no portable, reliable way to distinguish them in
86 general. However, in practice pipes always have a link count <=
87 PIPE_LINK_COUNT_MAX (unless someone attaches them to the file
88 system name space using fattach, in which case they're not really
89 pipes any more), so test for that as well.
91 On Darwin 7.7, pipes are sockets, so check for those instead. */
93 if (! ((HAVE_FIFO_PIPES
== 0 || HAVE_FIFO_PIPES
== 1)
94 && PIPE_LINK_COUNT_MAX
!= (nlink_t
) -1)
95 && (S_ISFIFO (st
.st_mode
) | S_ISSOCK (st
.st_mode
)))
98 int pipe_result
= pipe (fd_pair
);
104 int fstat_pipe_result
= fstat (fd_pair
[0], &pipe_st
);
105 int fstat_pipe_errno
= errno
;
108 if (fstat_pipe_result
!= 0)
110 errno
= fstat_pipe_errno
;
111 return fstat_pipe_result
;
113 check_for_fifo
= (S_ISFIFO (pipe_st
.st_mode
) != 0);
114 pipe_link_count_max
= pipe_st
.st_nlink
;
119 (st
.st_nlink
<= pipe_link_count_max
120 && (check_for_fifo
? S_ISFIFO (st
.st_mode
) : S_ISSOCK (st
.st_mode
)));