QProcess read and write

ⅰ亾dé卋堺 提交于 2020-01-04 05:41:47

问题


I am trying to read and write from a qprocess right now. I made a little test program that takes input and redisplays it on the screen in a loop. Here is my code from Qt

  QString path = "./test";

        tcd = new QProcess(this);
        QStringList args;
        args << "";
        tcd->start(path,args);

        if(!tcd->waitForStarted(3000))
        {
            stdoutput->append("<h1><font color=red>There was a problem starting the software, please try running the program again.</font></h1>");

        }
        tcd->write("hello\n");
        tcd->write("hello\n");
        tcd->write("hello\n");
        tcd->write("hello\n");
        //tcd->write("quit\n");

QObject::connect(tcd, SIGNAL(readyReadStandardOutput()), this, SLOT(appendTextBox()));

This won't work unless I send that last quit command (which terminates my test program).

Here's my read command:

void TCD2_GUI::appendTextBox(){
    stdoutput->append("new output available: \n");
    QByteArray newData = tcd->readAllStandardOutput();
    stdoutput->append(QString::fromLocal8Bit(newData));
}

if I send quit, I will get all the output from the program at once, including everything I have sent it.

What am I doing wrong here?

As per request, here is the code from the program:

int main(int argC[], char* argV[]){
    printf("Welcome!\n");
    char* input = malloc(160);
    gets(input);

    while(strcmp(input,"quit") != 0)
    {
        printf("Got input %s\n", input);
        gets(input);

    }

}

回答1:


From the doc:

Certain subclasses of QIODevice, such as QTcpSocket and QProcess, are asynchronous. This means that I/O functions such as write() or read() always return immediately, while communication with the device itself may happen when control goes back to the event loop. QIODevice provides functions that allow you to force these operations to be performed immediately, while blocking the calling thread and without entering the event loop.

...

waitForBytesWritten() - This function suspends operation in the calling thread until one payload of data has been written to the device.

...

Calling these functions from the main, GUI thread, may cause your user interface to freeze.

link



来源:https://stackoverflow.com/questions/4949548/qprocess-read-and-write

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!