Redirecting output of a C program to another C pro

2019-06-04 06:50发布

问题:

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.

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

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?

回答1:

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

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

You should do:

program2 `program1`

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

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

EDIT: 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`"


回答2:

I think this should also work:

$ program1 | xargs program2


回答3:

You said, “program2 takes a string as an argument.”

The pipe | system redefines the program's standard input, not argument.

To take the output of program1 as an argument to program2, use:

  program2 $(program1)

The $() (also the back-tick ` can be used, but there are reasons to avoid this) takes the output of a program and adds it to the current line, then re-evaluates it; so if program1 prints out "foo", the command to be run is program2 foo