1

I want to execute "docker run -it Image_name" from a C++ program. Is there any way to achieve this?

  • Spawning processes is a complicated subject. It tends to be platform-specific as well. This is especially true if you want to run in parallel with the child process, or read its output. If you are OK with running docker, not reading its output, and waiting for it, check out the `system` library function, which both Windows and UNIX support. – Myria Jul 29 '19 at 21:32
  • Also consider that `docker run` can extremely be easily used to take over a system, and frequently requires root privileges to run for this reason. I would try to avoid this path if at all possible. – David Maze Jul 29 '19 at 23:13

2 Answers2

0

Try as you do for simple system command from C++.

System("docker run -it Image_name")
Avinash
  • 41
  • 4
0

I can think of two ways you could achieve this.

For a quick-and-dirty approach, you can actually run commands from your C++ code. There seems to be a few ways to run commands with C++, but the system() function seems to be an easy way if you just want to run the command:

int main() {
    system("docker run -it Image_name");
}

Bare in mind you will need to make sure the docker executable is in your PATH environment variable. You will also need to consider what operating systems you want to support, a system call in Linux might not behave the same as in windows. It can be tricky to get system calls right.

For another method, using the docker engine's API directly. docker commands are sent to this API. You could connect directly to this API yourself and call the API the same way the docker run -it Image_name command would. The Engine API is documented here https://docs.docker.com/engine/api/v1.24/ . I believe the docker run -it Image_name command starts up what the API calls a "service".

The shell command will be the easiest approach. The Engine API approach would take more effort up front, but will result in cleaner, more robust code. The correct approach will depend on your situation.

liamdiprose
  • 433
  • 5
  • 14