tags:

views:

179

answers:

3

Hello,

I am trying to use a message queue for communication between two unrelated processes in Linux. I am aware that using a common key value will allow us to open the same message queue in both the unrelated processes. But the problem is that at times a key value corresponding to a message queue might already be used by some system utility. So I am using IPC_CREAT | IPC_EXEL flags to ensure that a new message queue is compulsorily created.

In case msgget() returns an error, I increment the key value and retry to create a new message queue, till it succeeds. Now, the problem is how do I communicate this successful key value to the other unrelated process which wants to operate on the same message queue.

Am I missing something? Has anyone faced similar issues before?

+2  A: 

Use ftok(3). It takes a pathname and an arbitrary integer id (uses only lower 8 bits, so a character is usually used) and generates a probably unique key_t. It's not guaranteed to be unique, but using the id you can use the same pathname and have prescribed increments for the id if there is a collision.

Typical execution would be:

Primary uses ftok(3) to obtain a key.

Primary uses the flags to specify it wants a new message queue. On error, increments the id and recalls ftok until it gets a suitable message queue. Message queue is created with permissions specific to the user/group that the secondary process runs as (as narrow as is possible, preferably unique to the process)

Secondary uses ftok to obtain the starting key, then uses msgget, incrementing the id and reusing ftok as determined beforehand until it successfully gets the message queue key.

Matt
+1  A: 

IIRC, this is exactly the problem that the ftok(3) is used to solve. The programs that need to communicate simply use a common path and key value. We used to pass the name of a FIFO on the command line to our programs. They would pass this into ftok() to generate the key for our shared memory segments.

D.Shawley
A: 

You could simply move into the 21st century and use a Posix message queue rather than a sysV one. Posix queues have names rather than obscure numbers. Under linux you can mount a filesystem to see them and remove them with "rm".

MarkR