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

C++ 在Linux中从C+;运行另一个程序+;节目,c++,linux,unix,terminal,C++,Linux,Unix,Terminal,好的,我的问题是。假设我有一个简单的C++代码: #include <iostream> using namespace std; int main(){ cout << "Hello World" << endl; return 0; } 是否有办法从我的简单C++程序中做到这一点?比如说 #include <iostream> using namespace std; int main(){ ./prog ?? c

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

#include <iostream>
using namespace std;

int main(){
   cout << "Hello World" << endl;
   return 0;
}
是否有办法从我的简单C++程序中做到这一点?比如说

#include <iostream>
using namespace std;

int main(){
   ./prog ??
   cout << "Hello World" << endl;
   return 0;
}
#包括
使用名称空间std;
int main(){
/程序??
试试看:


您可以使用系统命令:

system("./prog");

您可以使用这样的系统调用:

如果使用用户输入作为参数,请小心,这是产生一些意外后果的好方法。清除所有内容

通常,系统调用可以被解释为不正确的形式。

您需要
system()
库调用;请参阅。例如:

#包括
int main(){
标准::系统(“./prog”);
返回0;
}
当然,确切的命令字符串取决于系统。

您也可以使用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;
}
#包括
内部主(空)
{
文件*handle=popen(“./prog”,“r”);
if(handle==NULL){
返回1;
}
char-buf[64];
尺寸读数;
而((readn=fread(buf,1,sizeof(buf,handle))>0){
fwrite(buf,1,readn,stdout);
}
pclose(手柄);
返回0;
}

可能与@hopia重复,而不是重复。您所指的是关于
system()的高级使用的问题
;这张海报只需要知道函数的存在。在该系统中,可能会安装一个std::。我如何获得新程序的pid?@Gil404:pid是一个Unix概念,并非所有操作系统都有。如果需要,请使用POSIX
fork
exec
,或您的操作系统的等效程序。
system("./prog");
#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;
}