Question: 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?

Answer: 
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.
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".