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

时间:2022-12-28 20:44:30

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服务器,我想从用户(在webservice内)执行此命令行。

Need help Appreciate

需要帮助欣赏

2 个解决方案

#1


21  

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)来运行命令,这就是为什么我在重载时删除了引号;无论如何,它们对于一个单词都是毫无意义的,并且将被shell删除,并且从未被启动过的程序看到过。

#2


4  

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

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

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

如果你需要来自这个过程的结果,这里有一个使用C的popen()的例子,或者你可以看一下Boost.Process的C ++方法。

#1


21  

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)来运行命令,这就是为什么我在重载时删除了引号;无论如何,它们对于一个单词都是毫无意义的,并且将被shell删除,并且从未被启动过的程序看到过。

#2


4  

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

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

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

如果你需要来自这个过程的结果,这里有一个使用C的popen()的例子,或者你可以看一下Boost.Process的C ++方法。