简体   繁体   English

使用stdin和stdout管道到同一C程序

[英]Piping to same c program using stdin and stdout

Let's say I have an executable called myProgram that reads from an input file and writes to an output file. 假设我有一个名为myProgram的可执行文件,该可执行文件从输入文件读取并写入输出文件。 A command line for this program looks like this: 该程序的命令行如下所示:

./myProgram -o outputfile inputfile

The argument to the -o option specifies an output file name; -o选项的参数指定输出文件名; if no such file exists then the program will create it. 如果不存在这样的文件,则程序将创建它。

What I was wondering is whether I can execute myProgram multiple times, piping the output of the one instance to the input of the next. 我想知道的是我是否可以多次执行myProgram,将一个实例的输出传递到下一个实例的输入。 For example, 例如,

./myProgram inputfile | ./myProgram -o outputfile

Is it possible to achieve this and if so, what would I have to implement? 是否有可能实现这一目标,如果是这样,我将必须执行什么? exec calls and forking? exec调用和分叉? just simple read and write calls? 只是简单的读写调用?

Pipes work by chaining stdin and stdout of multiple programs together. 管道通过将多个程序的stdin和stdout链接在一起来工作。

You need to modify your program to have the ability to read from stdin and write to stdout instead of to specific files. 您需要修改程序以具有从stdin读取并写入stdout而不是特定文件的能力。 Then you can use pipes. 然后,您可以使用管道。

The short answer is: yes, you can do this. 简短的答案是:是的,您可以这样做。

However, your program should then read its input from stdin and write to stdout. 但是,您的程序然后应从stdin读取其输入并写入stdout。 This means, arguments as input or output file will no longer be necessary. 这意味着不再需要将参数作为输入或输出文件。

./myProgram < inputfile > outputfile

or, to illustrate the chaining, 或者,为了说明链接,

./myProgram < inputfile | ./myProgram > outputfile

A widely spread combination is to read from stdin if no input file is specified and write to stdout if no outputfile or outputfile "-" is passed at the command line. 如果未指定输入文件,则广泛使用的组合是从stdin读取,如果未在命令行中传递outputfile outputfile“-”,则写入stdout。 This provides maximum flexibility. 这提供了最大的灵活性。

Having said that, if it is sensible to chain multiple instances of the same program depends of course largely on what this program does . 话虽如此,链接同一程序的多个实例是否明智,当然很大程度上取决于该程序的功能 For example, for a sorting program this doesn't seem to make much sense of course ;) 例如,对于排序程序,这似乎没有多大意义;)

与使用命令一起运行程序myProgram的两个实例绝对没有问题

./myProgram inputfile | ./myProgram -o outputfile

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM