4

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.

4

3 回答 3

10

一种约定是使用ftok()man生成唯一密钥

ftok() 函数使用由给定路径名命名的文件的标识(必须引用现有的、可访问的文件)和 proj_id 的最低有效 8 位(必须为非零)来生成 key_t 类型 System V IPC 密钥,适用于 msgget(2)、semget(2) 或 shmget(2)。

当使用相同的 proj_id 值时,命名同一文件的所有路径名的结果值相同。当(同时存在的)文件或项目 ID 不同时,返回的值应该不同。

于 2010-01-15T00:16:42.713 回答
1

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.

于 2010-01-15T00:14:06.760 回答
1

对于“全球”资源,我附议 jspcal 的ftok()答案,他在我之前得到了 :)

如果你有一堆相关的进程(即一个父进程和一堆子进程)并且它们应该共享一个队列,那么你应该调用 msggetIPC_PRIVATE来创建一个带有未使用键的队列并将句柄返回给它。

于 2010-01-15T00:20:49.150 回答