How to determine the destination of standard output?

Guy Harris guy at auspex.auspex.com
Sun Feb 10 06:31:21 AEST 1991


>To check if it is going to a pipe, you may have to use the
>stat(2),stat(5) (or actually fstat()) system call on file descriptor 1,
>and look at the st_mode field, in particular, the S_IFIFO bit field
>to tell if stdout is a pipe.

Well, that works on many systems, but not all systems; a better test for
"is this a pipe" may be to do "lseek(fd, 0L, 1)" and see if it fails
setting "errno" to ESPIPE.

>The st_mode field will also tell you if it is going to a character or
>block device, or if it is a regular file...

Yup, and note that the correct way to test for a given file type is

	if ((statbuf.st_mode & S_IFMT) == <the type>)

*NOT*

	if (statbuf.st_mode & <the type>)

Most of you probably already know that, but every so often I see code
written by somebody who didn't, so....

If you have a POSIX-conforming system, you should use the "S_ISxxx"
macros to test for a given file type instead.



More information about the Comp.unix.programmer mailing list