Reputation: 3822
I have a binary that reads input with gets().
I would like to execute it using system() in my own program and pipe input to it. How would this be possible?
On command line I would just do echo 'blabla' | ./a.out
. Now I want to basically do the same inside a C program, where the blabla is generated in that program, then a.out is executed and blabla piped to it.
I can not change the first program to accept command line arguments.
Upvotes: 1
Views: 311
Reputation: 15501
Remember that system
actually runs a shell, so you can execute any shell command you want, including a pipeline. Unless you're generating output that you need to send in a loop or something like that, popen
provides no advantage (in particular, it does not allow you to write to the program's stdin
and also read from it's stdout
). So you can just use system
like this:
// generate the string you want to send
char str[256] = "blabla";
// sprintf it into a command string
char cmd[256];
sprintf(cmd, "echo '%s' | ./a.out", str);
// send the command string to system
system(cmd);
Upvotes: 2
Reputation: 6214
I have a binary that reads input with gets().
Don't use it. gets()
is unsafe to use under any circumstances.
In response to your question, you can use popen()
to pipe input into a subprocess.
Upvotes: 4