PDA

View Full Version : Send Qt Signals when a unix domain socket is selectable



fabifi
27th May 2009, 18:20
Hello, my question is:
How to connect Unix domain socket to Qt slot so that when the socket is SELECTABLE a Qt signal is sent?

I had already have a look to QLocalSocket and QSocketNotifier, but without any success.

Any hints?

Thanks.

Fabi

wysota
27th May 2009, 22:03
QSocketNotifier is what you want. Look at it again :)

fabifi
27th May 2009, 22:58
The point is that I wrote the code, I connected the signal QSocketNotifier::activated to my slot but it didn't worked at all..
I was not able to get those signals :(

I read about using unix signals and those are using a trick.. Do I need to use a trick for it too or what?

Thanks in advance

Fabi

wysota
28th May 2009, 00:02
Can we see the code you wrote?

By the way, you can also use QLocalSocket and expect readyRead() to be emitted when data becomes available.

fabifi
28th May 2009, 12:28
Finally I found a solution using QLocalSocket and connectToServer.
I used netstat -na to get the server name in my case /dev/shm/afed.

fabifi
28th May 2009, 19:20
unfortunately looks like that it doesn't work as expected :(

wysota
28th May 2009, 19:32
What exactly is wrong?

fabifi
29th May 2009, 09:58
Hi,
This morning I understood what was wrong, basically nothing in the code but just in my mind, I waited for readyRead signals when the reading buffer was already read by a C function in an external lib...
then everything is fine now.

Then just for helping other people who are looking for reading unix socket domain with Qt... I write here what I learned..
(Please comment this if something is wrong)

First of all, to read Unix domain socket with Qt we have to use QLocalSocket.

Unix domain socket have a path. You need that path to connect your local socket to the server.
I got that server path using netstat -na
In the netstat output, this line has been useful for me:
unix 2 [ ACC ] STREAM LISTENING 23611 /dev/shm/mydaemon


Then I wrote this in my QObject derived class:

Socket = new QLocalSocket(this);
Socket->connectToServer("/dev/shm/mydaemon", QIODevice::ReadOnly);
connect(Socket, SIGNAL(readyRead()), this, SLOT(readSocket()));

In my case I just need to read the output. I don't have to send anything so I used the option QIODevice::ReadOnly.


The server use send() to send data (in structure :/ ) then this is the code needed to read those data

void myClass::readSocket(){

QByteArray ba;
ba = Socket->readAll();

if (ba.isEmpty()){
return;
}
qDebug() << "read buffer" << ba.toHex() << ba.size();
myStruct *resp;
//Assuming valid this casting in the same machine.
resp = reinterpret_cast <myStruct*>(ba.data());
}

Then thanks for the help and if someone want to comment this code, please do it, in order to leave some info to other people interested in this topic.

thanks

fabi