How to choose a "key" for the interaction between processes in Linux?

Good afternoon...

I do my homework, which says that I have 5 processes; server, and the rest are clients. Each process must be called from a different executable file . I'm going to implement a two-way messaging solution, but the question is not about sending messages as such. Is there an elegant way to transfer a key between these various executables. those. when i call the following function:

int msgget(key_t key, int msgflg); 

How should other processes know the key?

It is normal for my homework to use a predefined key, but I would like to know how this can be done in a real program. Since "I understand," a conflict may occur if an unrelated process requests my key on any user machine.

+4
source share
3 answers

one convention is to use ftok () to create a unique key from man

The ftok () function uses the identifier of the file specified by pathname (which must refer to an existing, accessible file) and the least significant 8 bits proj_id (which must be non-zero) to generate a key_t type System V IPC key suitable for use with msgget ( 2), semget (2) or shmget (2).

The resulting value will be the same for all paths that name the same file when the same proj_id value is used. The return value must be different when (simultaneously existing) files or project identifiers are different.

+9
source

AFAIK, you usually generate a psuedorandom key for your program and paste it there. There are 2 ^ 32 possible keys, so the chance of a collision is pretty tiny.

If you need to guarantee an accidental collision, you usually use a named pipe instead of sending a message.

+1
source

For the "global" resources, I will second the jspcal ftok() answer that it got ahead of me :)

If you have a bunch of related processes (i.e. a parent and many children), and they should share the queue, then you should call msgget with IPC_PRIVATE , which will create a queue with an unused key and return the handle to it.

+1
source

All Articles