只允许将一个文件重定向到标准输入 [英] Only allow one file to be redirected to stdin
问题描述
我目前正在编写具有用法的C ++程序:
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.
推荐答案
进程没有什么可以看成权威地断定shell是否显式重定向了进程的标准输入而不是默认值.
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.
但是,当在POSIX平台上运行时,进程可以做出非常有根据的猜测,其中
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.
这不是100%可靠的.仍然可以通过精心制作的歌舞表演程序,并使用伪tty设备将管道连接到与交互式终端无法区分的流程标准输入,但是输入确实来自其他来源,但这很少见,对于典型的花园应用而言,isatty()
就足够了.因此,您的main()
可以检查isatty(0)
,如果是,则很好地表明输入尚未重定向.
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.
但是,请注意,如果isatty(0)
不是true,则可能会重定向标准输入,但是可能需要进行额外的侦查才能确定它是管道,纯文件还是其他内容.
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.
因此,您的总体游戏计划是:检查argv
是否指定文件名.如果是,则为isatty(0)
,那么您将要处理两个可能的输入文件.
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.
这篇关于只允许将一个文件重定向到标准输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!