Important: Please read the Qt Code of Conduct -

How to use QSocketNotifier on write mode on sockets

  • Hi,

    In one of our project, we are developping a software that needs to read and write on a CAN network. I would like to monitor both read and write events. Therefore, I decided to use a QSocketNotifier :

    bool CANController::init(const char* busid)  {
        struct sockaddr_can addr;
        struct ifreq ifr;
        m_socket = socket(PF_CAN, SOCK_RAW | SOCK_NONBLOCK, CAN_RAW));
        // Check if socket is accessible
        if((m_socket = socket(PF_CAN, SOCK_RAW | SOCK_NONBLOCK, CAN_RAW)) < 0) {
            qCritical() << "Error : cannot open socketcan socket.";
            return false;
        strcpy(ifr.ifr_name, busid);
        if(ioctl(m_socket , SIOCGIFINDEX, &ifr) < 0) {
            qCritical() << "Error : setting up the interface failed";
            return false;
        readNotifier  = new QSocketNotifier(m_socket , QSocketNotifier::Read, this);
        writeNotifier = new QSocketNotifier(m_socket , QSocketNotifier::Write, this);
        connect(readNotifier, &QSocketNotifier::activated,
                this, &CANController:readFrame);
        connect(writeNotifier, &QSocketNotifier::activated,
                this, &CANController::readFrame);

    When I only leave readNotifier, everything works fine but writeNotifier fires the activated signal all the time even if there is nothing that has been written !

    Does anyone have any idea of how to monitor what is written on the socket on write ?

    Thank you

    i use Qt 5.3

  • For anyone wondering, I got a trick to achieve my goal.
    If you want to monitor what is written and read on the interface, you better use two different sockets. The first one is only used for reading, the second one is only used for writing.

    Then, you only need one QSocketNotifier in Read mode.

  • Qt Champions 2020

    @Xatyrian said in How to use QSocketNotifier on write mode on sockets:

    all the time even if there is nothing that has been written !

    It is right behavior, please read how its work (e.g. about select() and so on).

    It need to use like this (e.g. for writing):

    1. Add data to be written to some internal buffer.
    2. Enable the write notifier.
    3. When the write notifier fired, just take all data from the buffer and send to ::send/::write.
    4. When the write notifier fired again, check for p.3.. If a buffer is empty - just disable wrute notifier.

    AFAIK, there are no ways to know that the data are written physically, to client.

    BTW: You can use qtserialbus module which implements the SocketCAN support (as I can see from your tag), just use a newest Qt version, as 5.3 is too old.

Log in to reply