0

Im quite new to c++ and QT and wanted to create a terminal application (Take in commands through a lineEdit and display the output in a textBrowser). I managed to do so using popen but whenever I ran a command which opened an external application (like firefox) my main program with freeze.

I realized I could run programs in the background using the c++ system function but then wouldn't get the output. I thought of a work around using the ">" operator for bash. My code is below.

void runCommand(QString qCmd) {
    qCmd += " > bashOutput.txt 2>&1 &";
    char *cmd  = qCmd.toLocal8Bit().data();

    system(cmd);

    std::ifstream myfile("bashOutput.txt");
    std::string line;

    if (myfile.is_open()) {
        QString result = "";
        while (getline(myfile, line)) {
            result += QString::fromStdString(line);
        }
        bash.addText(result); // adds result to QTextBrowser
    } else {
        errMsg("Can't open file");
    }

    myfile.close();
}

Any help would be appreciated, thanks!

Aryaman Arora
  • 65
  • 2
  • 7
  • 2
    Instead of using `system(cmd)`, use [`QProcess`](https://doc.qt.io/qt-5/qprocess.html). – R Sahu Aug 11 '21 at 17:06
  • You probably want to combine the duplicate with code that uses QProcess without [https://doc.qt.io/qt-5/qprocess.html#waitForFinished](https://doc.qt.io/qt-5/qprocess.html#waitForFinished) – drescherjm Aug 11 '21 at 17:16
  • 1
    Related: [https://stackoverflow.com/questions/62639158/qt-return-shell-command-result-non-blocking](https://stackoverflow.com/questions/62639158/qt-return-shell-command-result-non-blocking) – drescherjm Aug 11 '21 at 17:18

0 Answers0