美好的一天...
我正在做作业,其中指出我有 5 个进程;一个服务器,其余的都是客户端。 每个进程都应该由不同的可执行文件引发。我将实现一个双向消息传递解决方案,但问题不在于消息传递本身。是否有一种优雅的方式在这些不同的可执行文件之间传递密钥。即当我调用以下函数时:
int msgget(key_t key, int msgflg);
其他进程应该如何知道密钥?
我的作业可以使用预定的密钥,但我想知道如何在真实的程序。因为“我理解”的是,如果不相关的进程在某些用户的机器上请求我的密钥,则可能会发生冲突。
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.
发布评论
评论(3)
一种约定是使用 ftok() 从 人
one convention is to use ftok() to generate a unique key, from man
AFAIK,您通常会为您的程序生成一个伪随机密钥,并将其嵌入其中。有 2^32 个可能的键,因此发生冲突的可能性相当小。
如果需要保证不会发生意外冲突,通常会使用命名管道而不是消息传递。
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.
对于“全局”资源,我赞同 jspcal 的
ftok()
答案,他在我之前就得到了这个答案:)如果你有一堆相关的进程(即,一个父进程和一堆进程)孩子)并且他们应该共享一个队列,那么您应该使用
IPC_PRIVATE
调用 msgget ,这将创建一个具有未使用密钥的队列并返回其句柄。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.