Search code examples
socketsunixnetwork-programmingqt4qthread

Qt and threaded local server , why is the whole UI stuck?


Here's a minimal test case , I tried to start a local domain server , with QThread , so the UI shouldn't stuck. But when it's starting , i saw Listening output from qDebug() , but the widgets added from form editor totally disappeared , everything went slow (e.g resizing the window) , if i remove thread.start() , the UI shows up and functions well.

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    connect (&thread , SIGNAL(started()) , SLOT(setupServer()));
    thread.start();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::setupServer()
{
    struct sockaddr_un address;
    int socket_fd, connection_fd;
    socklen_t address_length;

    // create socket .. and create socket file ..
    // bind ...
    // listen ..

    qDebug() << "Listening ..";

    while((connection_fd = ::accept(socket_fd,
                                    (struct sockaddr *) &address,
                                    &address_length)) > -1)
    {
        qDebug() << "Got an connection.";
        ::close (connection_fd);
    }

    // close socket and remove the socket file
}

Solution

  • The accept(2) syscall is by default blocking. You should take advantage of the multiplexing syscall poll(2) or select(2) used by the QApplication's exec event loop.

    See this question and use the QtNetwork module.