【问题标题】:Erlang port doesn't process C++/Qt reply correctlyErlang 端口无法正确处理 C++/Qt 回复
【发布时间】: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


    【解决方案1】:

    我对 C++ 没有太多经验,但您似乎没有从端口刷新数据。 (而且"~n" 不是 C++ 中的新行,这不是案例,因为您使用 stream 模式而不是 line。)

    【讨论】:

    • 是的,您需要显式刷新数据。
    • 感谢 Hynek 和 rvirding!但是我该怎么做呢?我在其官方文档中没有发现任何明确刷新端口的内容。
    • @MartinLee: 不,您不需要刷新 port 您必须刷新 stdout io 句柄中的输出,即在 MainWindow::on_pushButton_clicked 函数中的消息之后调用 fflush(stdout) .
    • @Hynek-Pichi-Vychodil:所以,我的 UPD 解决方案是正确的,对吧?
    猜你喜欢
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    • 2014-01-05
    • 1970-01-01
    • 2016-08-21
    相关资源
    最近更新 更多