从c++程序运行shell脚本会自动将shell脚本的输出显示到控制台吗

Will running a shell script from a c++ program automatically display the output of the shell script to the console?

本文关键字:脚本 shell 输出 显示 控制台 程序 c++ 运行      更新时间:2023-10-16

我正在学习一个Linux类,以前从未学习过c++。我的shell脚本基本上都是自己完成的,但我需要从c++程序中使用它。当我的shell脚本从命令行运行时,它会将我想要返回的结果输出到控制台。当我从c++程序运行它时,我的程序会编译并运行,但我没有得到任何输出。这是因为我的c++程序中出现了一些错误,还是因为c++和shell脚本的交互方式?

我看到了一些关于从shell脚本获取输出并在c++程序中使用它的问题,但我不想这么做。实际上,我的c++程序所做的就是运行shell脚本。

我只想把shell脚本的输出显示在控制台上。你能帮忙吗?如果需要,我可以发布我正在使用的代码。

C++:

#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main (int argc, char *argv[]) {
string arg;
arg = string(argv[1]);
if (argc >= 2) {
for (int i=2; i < argc; i++) {
string temp = string(argv[i]);
arg=arg+" "+temp;
}
}
string command;
command = "./findName.sh "+ arg;
//cout << command;
system("command");
return 0;
}

如果你想实时显示输出,你可以使用这样的东西:

FILE* outputStream;
char buffer[1024];
outputStream = popen(command,"r");
if (outputStream == NULL)
return 1; //couldn't execute command
while (fgets(buffer, sizeof(buffer), outputStream) != NULL) {
//read output line-by-line to buffer and display it
std::cout << buffer << std::endl;
}
pclose(outputStream);