从C++执行 bash 脚本并读取其输出 ubuntu sdk

Executing bash script from C++ and read its output ubuntu sdk

本文关键字:输出 ubuntu sdk 读取 C++ 执行 bash 脚本      更新时间:2023-10-16

我有一个 ubuntu 应用程序,我正在尝试从中执行 bash 脚本,但它似乎不起作用。我尝试使用 system() 执行此操作

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    int main(int argc, char *argv[])
    {
// tried both
        system("./script.sh");
       // system ("script.sh")
    }

另外,我尝试对此进行研究,但没有找到解决方案; 是否可以读取输出并在文本框中显示。

使用 popen()

FILE *script;
char line[LINESIZE];
script = popen("./script.sh", "r");
while (fgets(line, sizeof(line), script)) {
    ...
}
pclose(script);

运行脚本无关紧要。这将适用于任何 shell 命令。

对于任何希望在QT中执行此操作的人,这是我所做的:

 QProcess proc;
        proc.start("gnome-terminal", QIODevice::ReadWrite);
        if (proc.waitForStarted() == false) {
            qDebug() << "Error starting terminal process";
            qDebug() << proc.errorString();
            return (-1);
        }