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.
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.
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.
For "global" resources I'm seconding jspcal's ftok()
answer which he got in just ahead of me with :)
If you have a bunch of related processes (that is, a parent and a bunch of children) and they should share a queue, then you should call msgget with IPC_PRIVATE
which will create a queue with an unused key and return the handle to it.