简体   繁体   English

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

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

I have a ubuntu application and I'm trying to execute bash scripts from it but it doesn't seem to be working. 我有一个ubuntu应用程序,正在尝试从中执行bash脚本,但它似乎无法正常工作。 I tried doing this with system() 我试图用system()做到这一点

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>

    int main(int argc, char *argv[])
    {
// tried both
        system("./script.sh");
       // system ("script.sh")

    }

Also, i've tried researching this but did not find a solution; 另外,我尝试对此进行研究,但没有找到解决方案。 is it possible to also read the output and display in textbox. 是否还可以读取输出并显示在文本框中。

Use popen() . 使用popen()

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

It's not relevant that you're running a script. 您正在运行脚本与您无关。 This will work with any shell command. 这将适用于任何shell命令。

For anyone looking to do this in QT, here's what i did: 对于希望在QT中做到这一点的任何人,这就是我所做的:

 QProcess proc;

        proc.start("gnome-terminal", QIODevice::ReadWrite);

        if (proc.waitForStarted() == false) {
            qDebug() << "Error starting terminal process";
            qDebug() << proc.errorString();

            return (-1);
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM