I want to know how I should go about performing an action in a C program if my input was redirected. For example, say I have my compiled program "prog" and I redirect an input "input.txt" to it (I do ./prog < input.txt
).
How do I detect this in code?
You can't, in general, tell if input has been redirected; but you can distinguish based on what type of file stdin is. If there has been no redirection, it will be a terminal; or it could have been set up as a pipe
cat foo | ./prog
, or a redirection from a regular file (like your example), or a redirection from one of a number of types of special files (./prog </dev/sda1
redirecting it from a block special file, etc).So, if you want to determine if stdin is a terminal (TTY), you can use
isatty
:If you want to distinguish between other cases (like a pipe, block special file, etc), you can use
fstat
to extract some more file type information. Note that this doesn't actually tell you whether it's a terminal, you still needisatty
for that (which is a wrapper around anioctl
that fetches information about a terminal, at least on Linux). You can add the following to the above program (along with#include <sys/stat.h>
) to get extra information about what kind of file stdin is.Note that you will never see a symlink from a redirection, as the shell will have already dereferenced the symlink before opening the file on behalf of your program; and I couldn't get Bash to open a Unix domain socket either. But all of the rest are possible, including, surprisingly, a directory.