简体   繁体   English

C语言编程。 如何读取我的程序中来自另一个程序的输入(通过管道)?

[英]C programming. How to read input in my program that comes from another program (via pipe)?

Here is what I try to run: (echo echo abc;echo echo def;echo echo ghi)|./myprogram 这是我尝试运行的内容:(echo echo abc; echo echo def; echo echo ghi)| ./myprogram

So input to myprogram comes from a pipe. 因此,myprogram的输入来自管道。

I am trying to read it as: 我正在尝试将其读取为:

while (fgets(line, MAXLINE+1, stdin)){
...
}

But as I understand input that comes to my program is now stdin, right? 但是据我了解,程序输入现在是stdin,对吗? So it does not work. 因此它不起作用。 I am not sure how to change my program so it works with input that is coming from another program. 我不确定如何更改程序,因此它可以与来自另一个程序的输入一起使用。

Thank you! 谢谢!

What you posit is exactly how you should do it. 您所假设的正是您应该如何做。 By piping information into your program, it's mostly indistinguishable (a) from regular input, as the following transcript shows: 通过将信息传递到程序中,它与常规输入几乎没有区别(a) ,如以下记录所示:

pax$ cat testprog.c
#include <stdio.h>
int main (void) {
        char line[1000];
        while (fgets (line, sizeof(line), stdin)) {
                printf ("%s", line);
        }
        return 0;
}

pax$ gcc -o testprog testprog.c

pax$ ( echo echo abc;echo echo def;echo echo ghi ) | ./testprog
echo abc
echo def
echo ghi

(a) There are ways to tell, such as with isatty() but you have to expend some effort. (a)可以通过isatty()等方法进行判断,但是您必须付出一些努力。 Mostly, input from a file or pipe or device can be treated as if you were entering it on the keyboard yourself. 通常,可以将文件,管道或设备的输入视为自己在键盘上输入。

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

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