The basic idea of a message queue or a mailbox is simple:Two (or more) processes can exchange information via access to a common system message queue. The sending process places via some message-passing module a message onto a queue which can be read by another process.
Each message is given an identification or type so that processes can select the appropriate message. Process must share a common key in order to gain access to the queue in the first place.
IPC messaging lets processes send and receive messages, and queue messages for processing in an arbitrary order. Unlike the file byte-stream data flow of pipes, each IPC message has an explicit length.Messages can be assigned a specific type. Because of this, a server process can direct message traffic between clients on its queue by using the client process PID as the message type.
Before a process can send or receive a message, the queue must be initialized through the msgget function and the operations to send and receive messages are performed by the msgsnd() and msgrcv() functions, respectively.
Initialising a message Queue
The msgget() function initializes a new message queue:
int msgget(key_t key, int msgflg)
msgget() returns the message queue ID on success, or -1 on failure (and it sets errno, of course).The first, key is a system-wide unique identifier describing the queue you want to connect to (or create). Every other process that wants to connect to this queue will have to use the same key. The other argument, msgflg tells msgget() what to do with queue in question. To create a queue, this field must be set equal to IPC_CREAT bit-wise OR'd with the permissions for this queue.
What about this key nonsense? How do we create one? one way is to use the ftok() function which generates a key from two arguments:
key_t ftok(const char *path, int id);
Basically, path just has to be a file that this process can read. The other argument, id is usually just set to some arbitrary char, like 'A'. The ftok() function uses information about the named file and the id to generate a probably-unique key for msgget(). Programs that want to use the same queue must generate the same key, so they must pass the same parameters to ftok().
the example showing the use of ftok() and msgget()
#include sys/msg.h
key = ftok("/home/beej/somefile", 'b');
msqid = msgget(key, 0666 | IPC_CREAT);
In the above example, I set the permissions on the queue to 666 (rw-rw-rw-) ie.,110 110 110.
Note:the three permission possible is r w x...read,write,execute. the above permission rw-rw-rw-
allows the root,user and group respectively to read and write only but not execute.
msqid will be used to send and receive messages from the queue.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.