20 Oct 2014

What is message queues key master sending receiving destroying sample



1.2. "Are you the Key Master?"

What about this key nonsense? How do we create one? Well, since the type key_t is actually just a long, you can use any number you want. But what if you hard-code the number and some other unrelated program hardcodes the same number but wants another queue? The solution is to use the ftok() function which generates a key from two arguments:
key_t ftok(const char *path, int id);
Ok, this is getting weird. 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 (like inode number, etc.) 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().
Finally, it's time to make the call:
#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 (or rw-rw-rw-, if that makes more sense to you). And now we have msqid which will be used to send and receive messages from the queue.

1.1. Where's my queue?

Let's get something going! First of all, you want to connect to a queue, or create it if it doesn't exist. The call to accomplish this is the msgget() system call:
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 arguments are a little weird, but can be understood with a little brow-beating. 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. (The queue permissions are the same as standard file permissions—queues take on the user-id and group-id of the program that created them.)
A sample call is given in the following section.

How To Become Expert In Linux/Unix

No comments:

Post a Comment