How do I tell if STDIN is a PIPE?
der Mouse
mouse at thunder.mcrcim.mcgill.edu
Thu May 30 20:11:53 AEST 1991
In article <1991May26.172328.713 at arizona.edu>, jjr at ace.ece.arizona.edu (Jeffrey J. Rodriguez) writes:
> How do I tell whether stdin is coming from a pipe?
Difficult. Under some systems, a "pipe" is not a distinguishable
thing; in particular, BSD implements pipes as connected pairs of
sockets, so a pipe appears identical to any other socket connection (of
the same address family, of course).
> There must be some system call I can use from a C program. My
> problem is that lseek & fseek won't work with a pipe. Therefore, I
> need to check stdin to see if it is coming from a pipe.
Ah. You don't care whether it's a pipe, you only care whether it's
seekable. There are lots of things it could be, and pipes aren't the
only unseekable ones (nor are plain files the only seekable ones).
The simplest thing to do is, as someone else recommended, try to seek:
a good harmless seek to try is a relative seek to 0 bytes from the
current position.
But whether even that is really what you want depends on what you're
doing. Even when you're connected to something seekable, it may change
between one read and the next - even if it's a plain file. You should
balance the dangers and decide what you *really* want: do you want to
reread the input, do you want to see what's somewhere else in the
"file", just what *do* you want to do?
> If stdin is coming from a pipe, then what is the best way to do a
> seek?
There is none, in general.
> If the input data is not ASCII, then a loop of getchar() won't work.
What's ASCII got to do with it? getchar() is perfectly happy reading
binary data. (You aren't making the mistake of thinking getchar()
returns a char, are you? (It doesn't; it returns an int.))
A loop with getchar() can't possibly seek any way but forwards. If
that's all youi want to do, you *can* do it on a pipe - or a file, or
pretty much anything else. Just be prepared to get EOF while reading,
of course.
der Mouse
old: mcgill-vision!mouse
new: mouse at larry.mcrcim.mcgill.edu
More information about the Comp.unix.programmer
mailing list