views:

133

answers:

3

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.

+1  A: 

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.

Anon.
Thats why came to my mind actually, maybe I am assuming that collision could happen where in fact it doesn't happen in practice. I would choose this answer if no other solution is proposed :)
AraK
+5  A: 

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.

jspcal
Thanks. Excuse me If I understood the answer incorrectly, but how do I share that "generated key" between the executables? i.e. After I get the key in the server, how would I communicate it to one of the clients?
AraK
By running ftok with the same argument in the clients.
hobbs
@hobbs If I read the description correctly, it says that there must exist a file in that path, so predetermined random "long" string is not an option.
AraK
+1  A: 

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.

hobbs