在Linux下使用bash脚本将C程序的输出重定向到另一个C程序 [英] Redirecting output of a C program to another C program with a bash script under Linux

查看:53
本文介绍了在Linux下使用bash脚本将C程序的输出重定向到另一个C程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了两个简单的C程序,program1打印出一个预定义的字符串,program2将一个字符串作为参数并将其写入文件.

I have written two simple C programs, program1 prints out a predefined string and program2 takes a string as an argument and writes that string into a file.

我想做的是获取program1的输出并将其传递给program2.我看过bash教程,唯一能找到的解决方案是:

What I'm trying to do is to take the output of program1 and pass it to program2. I've been through bash tutorials and the only solution I could find was:

program1 | program2

这应该可以工作,但是我遇到了段错误.所以我尝试了一下,它就可以了.

This is supposed to work but I get a segmantation fault. So I tried this and it works.

program1 | program2 abc

您可以猜测这会导致包含字符串"abc"的输出文件.程序1 |program2似乎很简单,但我想我在这里遗漏了什么?

As you can guess this results in an output file containing the string "abc". program1 | program2 seems straightforward but I guess I'm missing something here?

推荐答案

| 使右侧的程序(作为STDIN)读取左侧的程序的STDOUT.

| makes the program to the right read (as STDIN) the STDOUT of the program on the left.

但是您的 program2 根本不读取STDIN.它读取参数(不是STDIN).

But your program2 does not read STDIN at all. It reads the arguments (which are NOT STDIN).

您应该这样做:

program2 `program1`

Bash评估program1(当它看到反引号时),并将其作为arg传递给program2.

Bash evaluates program1 (when it sees the backquotes), and passes it as an arg to program2.

在键盘上,反引号(`)位于"1"键的左侧,并且位于我的LEFT TAB键的上方.

On my keyboard the backtick (`) is to the left of the "1" key, and above my LEFT TAB key.

如果 program1 的字符串输出包含空格,并且您希望将整个字符串解释为一个参数,请用"或"引号:

If the string output of program1 contains spaces and you want the entire string to be interpreted as one argument, quote the string with "" or '':

program2 "`program1`"

这篇关于在Linux下使用bash脚本将C程序的输出重定向到另一个C程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆