【发布时间】:2011-12-14 20:15:02
【问题描述】:
我正在尝试通过 Erlang 端口将 Erlang 程序与简单的 Qt 窗口应用程序通信。
问题是 Qt 窗口事件 (on_pushButton_clicked()) 的结果仅在窗口关闭后才显示在 Erlang 端口中,而不是在按下按钮时:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "stdio.h"
#include "choosefileform.h"
#include <iostream>
using namespace std;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
fprintf(stdout, "window_input:");
printf(ui->lineEdit->text().toAscii());
printf("~n");
ChooseFileForm* fn = new ChooseFileForm();
this->close();
fn->show();
}
Erlang(这里发送消息什么都不做,我们有兴趣从 Qt 获取数据):
connect(Message) ->
Cmd = "./myqtwindowapp \n",
Port = open_port({spawn,Cmd}, [stream,use_stdio,exit_status]),
Payload = string:concat(Message, "\n"),
erlang:port_command(Port, Payload),
receive
{Port, {data, Data}} ->
?DBG("Received data: ~p~n", [Data]),
Other ->
io:format("Unexpected data: ~p~n", [Other])
after 15000 ->
?DBG("Received nothing~n", [])
end.
运行这个并在窗口中填充文本字段的结果是什么(Erlang什么都没有,只是在receive子句中等待):
只有当我手动关闭窗口时 Erlang 才会说:
Received data: "window_input:hello"
那么,我为什么不立即将数据从 Qt 获取到 Erlang 端口?
UPD。解决方案:
解决方案是flush() Qt 的缓冲区:
我用的不是fprintf(stdout, "window_input:");
cin >> c;
cout << c;
cout.flush();
它奏效了。
附:但是,我不明白为什么在控制台中测试同一个 Qt 应用程序时没有发生这个问题 - 它立即返回数据,我填写了窗口中的文本字段(即事件)。
【问题讨论】:
标签: c++ qt erlang stdin erlang-ports