[英]Reading asynchronously from stdin with Qt
我想用Qt從stdin異步讀取。 我不想使用單獨的線程或必須設置定時器來定期檢查文件描述符是否有數據。 我怎樣才能做到這一點?
如果您閱讀Qt文檔,它說您不能這樣做,因為它不可移植。 為什么不使用假定您可以控制另一端的TCP套接字。 最糟糕的情況是,您可以進行代理申請。
如果要將stdin / stdout / stderr I / O與QT事件循環集成,可以:
read(2)
和write(2)
或者自己執行I / O. QFile
對象並調用bool QFile::open ( int fd, OpenMode mode )
來與它進行Qt樣式的I / O. 也許這適合你:
https://github.com/juangburgos/QConsoleListener
像這樣工作:
#include <QCoreApplication>
#include <QDebug>
#include <QConsoleListener>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// listen to console input
QConsoleListener console;
QObject::connect(&console, &QConsoleListener::newLine, &a, [&a](const QString &strNewLine) {
qDebug() << "Echo :" << strNewLine;
// quit
if (strNewLine.compare("q", Qt::CaseInsensitive) == 0)
{
qDebug() << "Goodbye";
a.quit();
}
});
qDebug() << "Listening to console input:";
return a.exec();
}
如果您願意使用boost,則可以使用Asio庫。 分配給STDIN_FILENO
posix::stream_descriptor
工作得很好。 另見這個答案 。
嘗試使用QSocketNotifier
QSocketNotifier * notifier = new QSocketNotifier( FDSTDIN, QSocketNotifier::Read );
connect(notifier, SIGNAL(activated(int)), this, SLOT(readStdin(int)));
正如克里斯指出的那樣,最好的方法是有一個單獨的線程,它將從stdin
輪詢並填充數據以供顯示或處理線程處理。
現在你可以設置QTimer
並為timeout()
信號設置一個處理程序,以便從stdin
讀取。 實施方法完全取決於您。
對於第二種方法,您可以查看QT的計時器類文檔 ,以獲取有關如何執行此操作的示例。 要記住的一件事是在處理完成后實際重啟計時器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.