1

I am starting a QProcess to open cmd.exe.

I want to write to std in to send commands to cmd.exe, and I want to recieve it's output.

QProcess mProcess = new QProcess(this);
mProcess->setReadChannelMode(QProcess::SeparateChannels);
mProcess->start("cmd");

QApplication::processEvents();
QString s(mProcess->readAllStandardOutput());
writeToConsole(s);

This all works just fine. The process starts, I get output. However, I can't now write to the process anymore. I have looked over QProcess documentation and I don't see any way to write to standard in. I've tried mProcess->write(data); but that didn't do anything.

How do I write to standard in to the running process?

1

3 Answers 3

3

You have to use write function only to write in to the standard in.

But the important thing is you have to close the write channel using void QProcess::closeWriteChannel().

Look into below documentation.

http://doc.qt.io/qt-5/qprocess.html#closeWriteChannel

2
  • 1
    Ok, but if I'm closing the write channel, then how do I open it again. I'm not trying to send just one set of commands, I'm trying to essentially make a terminal with commands and responses going back and forth, but all Qt appears to be geared for is one and done read or writes.
    – granitdev
    Aug 4, 2017 at 17:54
  • Call "start" again. The "start" call implicitly opens the write channel. Aug 4, 2017 at 18:08
0

You should wait for operations to finish before moving on to the next action.

QProcess mProcess = new QProcess(this);
mProcess->setReadChannelMode(QProcess::SeparateChannels);

//Start the process
mProcess->start("cmd");
QApplication::processEvents();
mProcess->waitForStarted();

// Read the output
mProcess->waitForReadyRead();
QString output(mProcess->readAllStandardOutput());
mProcess->closeReadChannel();

// Write the data
mProcess->write(output);
mProcess->waitForBytesWritten();
mProcess->closeWriteChannel();

// Wait for finished
mProcess->waitForFinished();

It seems strange to send the output directly back into the program being executed. Alternatively you could connect the void QIODevice::readyRead() signal to a slot where the output can be handled elsewhere.

0

The mistake I was making here was not putting \n on the end of the multiple commands.

''''
        // 1st command
        mProcess->write(output1 + "\n");
        mProcess->waitForBytesWritten();


        // 2nd command
        mProcess->write(output1 + "\n");
        mProcess->waitForBytesWritten();

       // Wait for finished
       mProcess->waitForFinished();


       mProcess->closeWriteChannel();
''''

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.