如何从 C++ 程序执行命令行命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8832326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 19:10:49  来源:igfitidea点击:

How can I execute a command line command from a C++ program

c++ubuntu

提问by Angel Dream

How can I execute the command line "asterisk -rx "reload"" in c++? Please help. I need an example. I am working on ubuntu server and I want to execute this command line from a user (inside a webservice).

如何在 C++ 中执行命令行“asterisk -rx“reload””?请帮忙。我需要一个例子。我正在 ubuntu 服务器上工作,我想从用户(在 web 服务内)执行此命令行。

Need help Appreciate

需要帮助 欣赏

回答by unwind

Sounds like a trivial use-case for the system()function:

听起来像是该system()函数的一个微不足道的用例:

system("asterisk -rx reload");

If you need very fine-grained control of the child process there are better ways, but this is simple to get going.

如果您需要对子进程进行非常细粒度的控制,有更好的方法,但这很容易上手。

This call starts a shell (such as bash) to run the command, which is why I removed the quotes around reload; they're pointless for a single word and will be removed by the shell and never seen by the started program, anyway.

这个调用会启动一个 shell(比如 bash)来运行命令,这就是我删除了reload;周围的引号的原因。它们对于单个单词毫无意义,并且会被 shell 删除,无论如何都不会被启动的程序看到。

回答by Alex Reynolds

system("asterisk -rx \"reload\"")would probably work, if you don't need standard output or error from the process.

system("asterisk -rx \"reload\"")如果您不需要标准输出或过程中的错误,可能会起作用。

If you need results from the process, hereis an example of using C's popen(), or you could look at Boost.Processfor a C++ approach.

如果您需要流程的结果,这里有一个使用 C 的示例popen(),或者您可以查看Boost.Process以获取 C++ 方法。