欺骗 Unix 命令行程序接受文件流
假设的情况。我在 *nix(linux、BSD 等)中有一个命令行程序。它的编写方式是为了将一个文本文件作为参数传递给它。
$ program file.txt
运行该程序,它会查看 file.txt
中的文本。
是否有可能“欺骗”该程序接受来自文件流的输入而不是通过磁盘读取文件?我很习惯使用unix管道来做东西,但是它们的内部结构仍然有些神秘,所以我不能(明确地)对上述问题说是或不是。
Hypothetical situation. I have a command line program in *nix (linux, BSD, etc.). It was written so that you pass it a text file as an argument
$ program file.txt
Run the program, it looks at the text in file.txt
.
Is it possible to "trick" this program into accepting input from a file stream rather than reading a file via disk? I'm pretty comfortable using unix pipes to do stuff, but there's still something a little mysterious about their internals that make it so I can't say (definitively) yes or not to the above question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
bash
允许您执行此操作:它使用
otherprogram
的输出作为传递给program
的文件内容。bash
lets you do this:This uses the output of
otherprogram
as the contents of a file passed toprogram
.您可能对命名管道感兴趣:
相当于:
You may be interested in named pipes:
is equivalent to:
如果您的
程序
未编码为接受标准输入,即使您使用命名管道或进程替换,它也不会工作if your
program
is not coded to accept standard input, it won't work even if you use named pipes or process substitution除了其他答案的 shell 管理的诡计之外:
一些 UNIX 系统有特殊文件
/dev/stdin
,你可以运行例如其他(例如 linux)可能有
/proc/ self/fd/0
可以以相同的方式使用。如果在打开命令行上的文件之前关闭 stdin,这两种方法都会失败,但这种情况极为罕见。更有可能的是它会失败,因为程序期望
seek()
该文件,这在管道上不起作用。如果您的 shell 是 zsh,您还有另一个选择。
这将完成设置临时输入文件并在程序终止后删除它的所有麻烦。这将与
seek()
一起使用,但可能会暂时占用更多空间。In addition to the shell-managed trickery of the other answers:
Some unix systems have the special files
/dev/stdin
, and you can run e.g.Others (e.g. linux) may have
/proc/self/fd/0
which may be used the same way.Both of these will fail if
stdin
is closed before the file on the command line is opened, but this will be an extremely rare occurrence. Much more likely will be it failing because the program expects toseek()
the file, which does not work on pipes.If your shell is zsh, you have another option.
Which will do all the bother of setting up a temporary input file and removing it after
program
terminates. This will work withseek()
, but may temporarily take more space.