从 C++ 程序在 Linux 中运行另一个程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9120596/
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-06 04:20:53  来源:igfitidea点击:

Run Another Program in Linux from a C++ Program

c++linuxunixterminal

提问by Vincent Russo

Okay so my question is this. Say I have a simple C++ code:

好的,所以我的问题是这个。假设我有一个简单的 C++ 代码:

#include <iostream>
using namespace std;

int main(){
   cout << "Hello World" << endl;
   return 0;
}

Now say I have this program that I would like to run in my program, call it prog. Running this in the terminal could be done by:

现在说我有一个我想在我的程序中运行的程序,称之为 prog。在终端中运行它可以通过以下方式完成:

./prog

Is there a way to just do this from my simple C++ program? For instance

有没有办法从我的简单 C++ 程序中做到这一点?例如

#include <iostream>
using namespace std;

int main(){
   ./prog ??
   cout << "Hello World" << endl;
   return 0;
}

Any feedback would be very much obliged.

非常感谢任何反馈。

采纳答案by J. C. Salomon

You want the system()library call; see system(3). For example:

你想要system()图书馆的电话;见系统(3)。例如:

#include <cstdlib>

int main() {
   std::system("./prog");
   return 0;
}

The exact command string will be system-dependent, of course.

当然,确切的命令字符串将取决于系统。

回答by James McLaughlin

Try system(3):

尝试系统(3)

system("./prog");

回答by elimirks

You could us the system command:

您可以使用系统命令:

system("./prog");

回答by gmoney

You could use a system call like this: http://www.cplusplus.com/reference/clibrary/cstdlib/system/

您可以使用这样的系统调用:http: //www.cplusplus.com/reference/clibrary/cstdlib/system/

Careful if you use user input as a parameter, its a good way to have some unintended consequences. Scrub everything!

如果您使用用户输入作为参数,请小心,这是产生一些意外后果的好方法。擦洗一切!

Generally, system calls can be construed as bad form.

通常,系统调用可以被解释为错误的形式。

回答by xda1001

You can also use popen

您也可以使用 popen

#include <stdio.h>

int main(void)
{
        FILE *handle = popen("./prog", "r");

        if (handle == NULL) {
                return 1;
        }

        char buf[64];
        size_t readn;
        while ((readn = fread(buf, 1, sizeof(buf), handle)) > 0) {
                fwrite(buf, 1, readn, stdout);
        }

        pclose(handle);

        return 0;
}