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

Vin*_*sso 13 c++ unix linux terminal

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

#include <iostream>
using namespace std;

int main(){
   cout << "Hello World" << endl;
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

现在说我有这个程序,我想在我的程序中运行,称之为prog.在终端中运行此操作可以通过以下方式完成:

./prog
Run Code Online (Sandbox Code Playgroud)

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

#include <iostream>
using namespace std;

int main(){
   ./prog ??
   cout << "Hello World" << endl;
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

任何反馈都非常有必要.

J. *_*mon 16

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

#include <cstdlib>

int main() {
   std::system("./prog");
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

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


xda*_*001 8

你也可以使用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;
}
Run Code Online (Sandbox Code Playgroud)


eli*_*rks 5

您可以使用系统命令:

system("./prog");
Run Code Online (Sandbox Code Playgroud)