-1

I'm using Qt and trying to execute a command using QProcess. However, I'm encountering a timeout issue where the process operation times out. I've set up my code as follows:

void HostDecoder::usingCmd_btn_clicked() {
    QString program = "C:\\Windows\\system32\\cmd.exe";
    QString hostname = ui->hostname->text();
    qDebug() << "hostname:" << hostname;

    QProcess qprocess;
    qprocess.startDetached(program, QStringList() << "ping" << hostname);

    if (qprocess.waitForStarted()) {
        if (qprocess.waitForFinished()) {
            QByteArray output = qprocess.readAllStandardOutput();
            qDebug() << "command output:" << output;
            // Handle the output
        } else {
            qDebug() << "Failed to execute the command.";
            // Error handling
        }
    } else {
        qDebug() << "Failed to start the command.";
        // Error handling
    }
}

The code outputs "Failed to start the command." and I'm not sure why. I suspect it may be due to not setting the working directory. How can I resolve this issue?

I have already tried setting the read channel using setReadChannel() and setReadChannelMode(), as well as setting the process channel mode to SeparateChannels. However, the issue still persists.

Any help or suggestions would be greatly appreciated! Thank you in advance.

Note: I'm looking for a solution specific to Qt and QProcess.

Please let me know if there's anything else I can provide to help clarify the issue. Thank you!

LEO
  • 1
  • 3
  • You're probably filling up the output buffer, you need to read from the buffer before calling `waitForFinished` – Alan Birtles Jul 04 '23 at 15:05
  • Do these answer your question? [Do I get a finished slot if I start QProcess using startDetached](https://stackoverflow.com/questions/298060/do-i-get-a-finished-slot-if-i-start-qprocess-using-startdetached), [Qt QProcess startDetached can't end process (bash session)](https://stackoverflow.com/questions/38509913/qt-qprocess-startdetached-cant-end-process-bash-session) – Abderrahmene Rayene Mihoub Jul 04 '23 at 15:34
  • Also, the setters you tried to use are not supported by [startDetached](https://doc.qt.io/qt-6/qprocess.html#startDetached), read the documentation for more. – Abderrahmene Rayene Mihoub Jul 04 '23 at 15:39

1 Answers1

1

startDetached is static function so waitForStarted is not applicable, you start one QProcess somewhere in background and then want to get info from the other, not so initialized object.

So just use start instead of startDetached to run external process in your current thread.

artaxerx
  • 244
  • 1
  • 3
  • 11