使用QTextStream以非阻塞方式读取stdin [英] using QTextStream to read stdin in a non-blocking fashion

查看:1677
本文介绍了使用QTextStream以非阻塞方式读取stdin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Qt,我试图以非阻塞的方式读取stdin流的内容。我使用QSocketNotifier在套接字接收到一些新数据时提醒我。通知程序的设置如下:

Using Qt, I'm attempting to read the contents of the stdin stream in a non-blocking fashion. I'm using the QSocketNotifier to alert me when the socket has recieved some new data. The setup for the notifier looks like this:

QSocketNotifier *pNot = new QSocketNotifier(STDIN_FILENO, QSocketNotifier::Read, this);
connect(pNot, SIGNAL(activated(int)), this, SLOT(onData()));
pNot->setEnabled(true);

onData()

void CIPCListener::onData()
{
    qDebug() << Q_FUNC_INFO;
    QTextStream stream(stdin, QIODevice::ReadOnly);

    QString str;

    forever
    {
    	fd_set stdinfd;
    	FD_ZERO( &stdinfd );
    	FD_SET( STDIN_FILENO, &stdinfd );
    	struct timeval tv;
    	tv.tv_sec = 0;
    	tv.tv_usec = 0;
    	int ready = select( 1, &stdinfd, NULL, NULL, &tv );
    	if( ready > 0 )
    	{
    		str += stream.readLine();
    	}
    	else
    	{
    		break;
    	}
    }

    qDebug() << "Recieved data:" << str;
}

正如你所看到的,我试图使用select告诉我什么时候用完数据读取。但是,实际上发生的是在读取第一行文本后,select()调用返回0。因此,例如,如果我写了5行文本到进程的stdin流,我只读过第一行。

As you can see I'm attempting to use the select() system call to tell me when I've run out of data to read. However, in practise what is happening is the select() call returns 0 after I've read the first line of text. So, for example, if I write 5 lines of text to the process's stdin stream, I only ever read the first line.

可能是什么问题?

推荐答案

行缓冲。

默认值是在\\\
。如果你写5行到你的进程,你的插槽被调用5次。如果你想避免,你必须调用setbuf(stdin,_IOFBF)。但是,即使这样也不能保证你可以在一个块中读取任意大量的数据。

Default is flushing after a "\n". If you write 5 lines to your process, your slot gets called 5 times. If you want to avoid that, you have to call setbuf(stdin, _IOFBF). But even then it is not guaranteed you can read arbitrarily large amounts of data in one chunk.

编辑:最好使用QTextStream :: atEnd选择,因为QTextStream有自己的内部缓冲区。

It would probably better to use QTextStream::atEnd() instead of select, since QTextStream has its own internal buffers.

这篇关于使用QTextStream以非阻塞方式读取stdin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆