Results 1 to 5 of 5
I am implementing an IPC mechanism using message queues (Sys V).
I can receive the messages using msgrcv() function. I am wondering how can I listen on the new messages. ...
- 01-26-2011 #1Just Joined!
- Join Date
- Dec 2010
- Posts
- 7
Listening Message Queues
I am implementing an IPC mechanism using message queues (Sys V).
I can receive the messages using msgrcv() function. I am wondering how can I listen on the new messages. I would like to implement a mechanism that would notify me when there is a new message in the queue for me and I will call the msgrcv() function to retrieve the message.
Thanks much!
- 01-26-2011 #2Just Joined!
- Join Date
- Dec 2010
- Posts
- 7
I think I found my answer... probably msgflg argument passed in to the function defines the behavior here:
int msgrcv ( int msqid, struct msgbuf *msgp, int msgsz, long mtype, int msgflg );
I was expecting a call back mechanism like receiving an event etc but seems like this the mechanism here.
One can still confirm
- 01-26-2011 #3Just Joined!
- Join Date
- Dec 2010
- Posts
- 7
OK, what I dont understand is that if I pass 0 as the msgflg, the msgrcv will block until a message arrives in the queue. In some cases, I might want to wake the msgrcv function and resume the execution a defined manner. How can I do that? Looks like you cannot pass a timeout parameter or such to wake after certain amount of time.
I found this on a website,
"The calling thread receives a signal that is to be caught; in this case a message is not received and the calling thread resumes execution in the manner prescribed in sigaction()."
Not sure what it means, though.
I cannot paste the link it since I am a newbie...
- 01-27-2011 #4Just Joined!
- Join Date
- Jun 2006
- Posts
- 47
It looks like you could benefit from 'pthread' functionality.
Create a message receiver thread that would always listen to incoming messages.
Each time a message arrives, call a callback function.
Meanwhile, your _main_ thread goes on, so you actually don't need no timeout functionality.
Note that in any case you can signal the receiver thread to break the msgrcv().
- 01-28-2011 #5Just Joined!
- Join Date
- Dec 2009
- Location
- California
- Posts
- 68
I agree with white_hound - using threads will make the solution much cleaner, however, if you want to implement a "timeout", you can do so using signals.
First, you'll need to write a function to execute when the time expires (the handler):
void timehandler(int dummy)
{
time_t currtime;
char *timeAsString;
time(&currtime);
timeAsString=ctime(&currtime);
write(1,timeAsString,TIMESTRINGLEN);
alarm(10);
}
Now, you need to install the handler:
sigaction(SIGALRM,(struct sigaction *)NULL, &action);
action.sa_handler=timehandler;
sigaction(SIGALRM,&action,(struct sigaction *)NULL);
Set the initial timeout:
alarm(10);
Now, call your msgrcv....
You need to check "errno" after the msgrcv. If it's set to EINTR, then your timeout expired...


Reply With Quote