granitdev
granitdev

Reputation: 146

Qt QProcess how to write to standard in?

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?

Upvotes: 1

Views: 7021

Answers (3)

Lee
Lee

Reputation: 1

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();
''''

Upvotes: 0

konakid
konakid

Reputation: 65

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.

Upvotes: 0

Pavan Chandaka
Pavan Chandaka

Reputation: 12761

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

Upvotes: 3

Related Questions