[comp.unix.questions] distinguishing pipes from files

gwyn@brl-smoke.ARPA (Doug Gwyn ) (11/22/87)

In article <454@rocksanne.UUCP> fuss@rocksanne.UUCP (William Fuss) writes:
>Can a process can recognize the "source" of its input/output ???

Yes, the usual way is to perform an fstat() system call on the
file descriptor, then use some of the macros defined in <sys/stat.h>
on the st_mode field of the data structure returned by fstat()
to determine the inode type (regular file, FIFO/pipe, directory,
etc.).

Another thing that is sometimes done to test whether a file
descriptor is associated with a terminal port is to do an
ioctl() to get terminal handler parameters.  If the ioctl()
fails, presumably the inode is not a terminal.  This is
usually packaged as isatty() in the UNIX C library.

rjnoe@uniq.UUCP (Roger J. Noe) (11/23/87)

In article <6712@brl-smoke.ARPA>, gwyn@brl-smoke.ARPA (Doug Gwyn ) writes:
> In article <454@rocksanne.UUCP> fuss@rocksanne.UUCP (William Fuss) writes:
> >Can a process can recognize the "source" of its input/output ???
> 
> Yes, the usual way is to perform an fstat() system call on the
> file descriptor, then use some of the macros defined in <sys/stat.h>
> on the st_mode field of the data structure returned by fstat()
> to determine the inode type (regular file, FIFO/pipe, directory,
> etc.).

That will certainly work and may in fact be the most general way of
determining the type of file that is open to a process.  If one is
merely concerned with the pipe/fifo versus other file type distinction,
a quick and dirty way is to use the lseek syscall.  For example, to
determine on System V if a process' standard input (must already be
open) is a pipe or fifo:
	#include <errno.h>
	if (lseek(0, 0L, 1) < 0L && errno == ESPIPE)
		/* then it's a pipe or fifo, else it's not */
which attempts to seek on fd 0 an offset 0L from "here" (1) and thus will
do nothing if it's neither a pipe nor fifo.  Note that there are other reasons
the seek might fail, but errno should be set to ESPIPE only in the case of
a pipe or fifo.
--
long tloc = 507314353L;
	Roger Noe			{ihnp4|clyde}!uniq!rjnoe
	Uniq Digital Technologies	+1 312 879 1566
	Batavia, Illinois  60510	41:50:56 N.  88:18:35 W.