Only allow one file to be redirected to stdin

2019-08-03 10:22发布

I am currently writing a C++ program with usage:

[prog]  - - - - - - - - - - - - read from stdin
[prog] [filename]   - - - - - - will test and open file
[prog] < [filename]   - - - - - will redirect the filename to stdin

I have written code to catch too many arguments, and everything works, except that if a user tries

[prog] < [filename] [filename]

it will open the second filename.

How do I prevent this case from happening. Thanks for your consideration.

2条回答
走好不送
2楼-- · 2019-08-03 10:40

There's nothing that a process can look at to authoritatively conclude whether or not the shell explicitly redirected the process's standard input away from the default.

But a process can make a very educated guess when running on a POSIX platform, where isatty() returns an indication whether the given file descriptor is attached to an interactive terminal. So, you can check if isatty(0) (standard input file descriptor #0); if so this means that the process's standard input is still attached to interactive keyboard input, and has not been redirected.

This is not 100% foolproof. It is still possible to go through an elaborate song-and-dance routine, and using a pseudo-tty device attach a pipe to a process's standard input that's indistinguishable from an interactive terminal, to the process, but the input really comes from some other source, but this is very rare, and for your typical garden-variety application, isatty() should be sufficient. So, your main() can check isatty(0), and if so it's a very good indication that the input has not been redirected.

Note, however, if isatty(0) is not true, the standard input is likely redirected, but additional sleuthing will be required to figure out if it's a pipe, or a plain file, or something else, perhaps.

So, your overall gameplan here is: check if your argv specifies a filename. If so, if isatty(0), then you've got two likely input files to deal with.

查看更多
相关推荐>>
3楼-- · 2019-08-03 10:45

How do I prevent this case from happening. Thanks for your consideration.

I don't think you can prevent this. A user can easily circumvent any such restrictions you might want to impose by using other tools to concatenate files. For examples, the user can easily use:

cat filename1 filename2 | program
查看更多
登录 后发表回答