I want to take an input, a bash command, and be able to execute that input from my CPP program. This is for school and we are not allowed to use "system" so I do not know any other way to do this. Also, the program can take up to 3 commands via pipe. I've looked up how to do this but it just gets more confusing. If there are any resources or a question similar to this that has been answered please link. Thanks.
Asked
Active
Viewed 680 times
-1
-
4There's a whole family of `exec` functions you can use. – tadman Apr 01 '21 at 21:44
-
1[This](https://man7.org/linux/man-pages/man2/execve.2.html) – Zoso Apr 01 '21 at 21:44
-
Won't work for intrinsic bash commands of course, only executables. But you can also run bash directly using `execxy()` and pass commands via a pipe for example. – πάντα ῥεῖ Apr 01 '21 at 21:47
-
Does [this](https://stackoverflow.com/a/4209206/1851678) answer your question? It uses the example of executing `echo` from the program. – Zoso Apr 01 '21 at 21:47
-
I apologize: I marked the wrong question as duplicate. But there are *many* questions on SO that can answer this. eg: https://stackoverflow.com/questions/5094063/fork-pipe-and-exec-process-creation-and-communication – William Pursell Apr 01 '21 at 22:21
1 Answers
0
Here is a similar question.
Basically, for the shell part, you are going to use fork
and some form of exec
(e.g., execve
) to get that to execute.
For pipes, you're going to have to use the pipe
command in C++, which will allow you to write and read from the pipe from separate children (in your case, up to two pipes, so you can create a 2x2 array of file descriptors, as a normal pipe is just a 2 element array). You should write the output of one program into the correct pipe and read it from the pipe in the next child once the first terminates.

Eric Miller
- 56
- 6