Shell commands from c++ without creating a new process every time?

Is there a way to run shell commands from c++ without creating a new process every time?
E.g. have a connection open and send and receive data

I don't think so. Functions like system() or popen() start a new shell process. And it's pretty obvious why that is: They pass the command to be executed to the shell as a command-line argument. For example, on Windows, system("some command") starts a new process with the command-line cmd.exe /c "some command".

If you need to execute multiple commands in the shell "at once" you could probably write them into a batch file (Windows) or shell script (Linux/Unix) and execute that file, e.g. via system().

https://en.wikipedia.org/wiki/Batch_file

You can "communicate" with a sub-process via pipe. In theory, it would be possible to write a program (e.g. shell) that accepts a stream of "commands" from the parent process via its stdin and returns the results to its parent process via its stdout. But I'm not aware of any "standard" shell that supports such facility.

Well, in a way SSH does exactly that, but over a network port :-D

You could write yourself a small "helper" program that accepts command from the stdin and executes them. But, if you want these commands to be executed in a shell, then your "helper" program would now be responsible for starting a new shell process for each of those commands. You don't really gain anything...

[EDIT]

As an aside, of course you can "chain" multiple shell commands via pipe operators, e.g.:
system("command_1 | command_2 | ... | commnad_n")

...if that is what you want ;-)
Last edited on
or &
system("command1 & command2");

it may be possible to start a heavily controlled cmd.exe process and continue to feed it commands. I am not sure. Not with system, but one of the bigger ones like create process family or spawn family or whatnot? Not having tried it, I can't say for sure.
Last edited on
Topic archived. No new replies allowed.