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

女生的网名这么多〃 提交于 2019-12-07 08:14:14

问题


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:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/2068498/how-to-choose-the-key-for-inter-processes-communication-in-linux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!