Wednesday, February 16, 2011

IPC: Message Queues

System V IPC consist of
Message Queues, Semaphores, Shared memory
Message Queues
Before talking about the what Message queues are, just like to point out disadvante of the other IPC, FIFO (named pipes)
Diadvantages of FIFO
1) data cannot be broadcased to mutliple receivers.
2) Cannot store Data
3) No message boundaries, Data is treaded as stream of bytes.

How to use
1) Create a Unique identification number, ftok() function
key_t ftok(const char *filenme, int id)
2) Get the resource
xxxget(ket_t key, int xxflg)
this syntax is common for all the ipc resources (msg, shm, sem)
3) All system V resources are controled by xxxctl function
xxxctl(int xxxid, int cmd, struct xxxid_ds *buffer)
The command argument can be anyone of these
IPC_STAT =>copy the infro the info from kernel structure to the pointer buffer
IPC_SET => write the info pointer by buffer to the message data structure
IPC_RMID => remove the object

4)
int msgget(key,msglag)
msgflog = IPC_CREATE | 0777
this 0777 is the queue permisssion
Message structure and message sending
struct my_msgbuf {
long mtype,
char any_data_arr[354]
};
Here you must should note that this "mtype" is necessary and used while receving the message.
"any_data_arr" can be any filed or you can add any number of the data elements in this structure later.

5) Send the mssage
msgsnd(msgid, &my_msbug, sizeof(my_msgbuf)-sizeof(long), flag)

flag = 0 or IPC_NOWAIT

6) Recevie the message
msgrcv(msgid, &my_msbug, sizeof(my_msgbuf)-sizeof(long), flag)
flag values are as below
0 = recevie the next message
postive = get the next message, whose mtype is equal to the flag
-ve = retrive the message whose abosolute values is less then or equal to the given value

7) When every thing is done do
msgctl(msqid, IPC_RMID, NULL)

http://beej.us/guide/bgipc/

No comments: