Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to choose the "Key" for inter-processes communication in Linux?

Good Day...

I am doing a homework which states that I have 5 processes; a server and the rest are clients. Each process is supposed to be sparked from a different executable. I am going to implement a two-way message passing solution, but the question is not about message passing per se. Is there an elegant way to communicate the key between those different executables. i.e. when I call the following function:

int msgget(key_t key, int msgflg);

How are other processes supposed to know the key?

It is OK for my homework to use a predetermined key, but I would like to know how it could be done in a real program. Because What "I understand" is there could happen a conflict if an unrelated process asks for the my key in some user's machine.

like image 231
Khaled Alshaya Avatar asked Dec 17 '22 03:12

Khaled Alshaya


2 Answers

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

The ftok() function uses the identity of the file named by the given pathname (which must refer to an existing, accessible file) and the least significant 8 bits of 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 is the same for all pathnames that name the same file, when the same value of proj_id is used. The value returned should be different when the (simultaneously existing) files or the project IDs differ.

like image 99
jspcal Avatar answered Jan 13 '23 13:01

jspcal


AFAIK, you'd typically generate a psuedorandom key for your program, and embed that in there. There are 2^32 possible keys, so the chance of a collision is fairly tiny.

If you need to guarantee no accidental collision, you'd typically use a named pipe instead of message passing.

like image 37
Anon. Avatar answered Jan 13 '23 13:01

Anon.