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?

granitdev
  • 136
  • 2
  • 13
  • [QProcess call write function failure](http://techqa.info/programming/question/15050462/qprocess-call-write-function-failure) – Vahagn Avagyan Jul 26 '17 at 20:42

3 Answers3

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

Pavan Chandaka
  • 11,671
  • 5
  • 26
  • 34
  • 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 04 '17 at 17:54
  • Call "start" again. The "start" call implicitly opens the write channel. – Pavan Chandaka Aug 04 '17 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.

konakid
  • 65
  • 1
  • 9
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();
''''
Lee
  • 1