开发者

What key to put on the receiver side of Linux message queues?

开发者 https://www.devze.com 2023-03-21 19:16 出处:网络
I have created a message queue and the sender part successfully creates and sends the message to the message queue.

I have created a message queue and the sender part successfully creates and sends the message to the message queue.

I have used IPC_PRIVATE as key in msgget() on the sender side.

Now my question is, what key to use in msgget() on the receiver side ?

Using IPC_PRIVATE on the receiver side as key in msgget() does not receive message and fails.

I should also mention that msgsnd() in the sender part indicates an error (returns -1), but when printing with perror(), the output is Success and the message is sent to the message queue successfully and can be seen using ipcs -q command at the terminal. I don't know why this happens.

 if(msgsnd(msqid,&msgp,88,IPC_NOWAIT)开发者_如何学C == 0)
          {
                  perror("\nsend : msgsnd FAIL");
                  msgctl(msqid,IPC_RMID,buf);
                  return 1;
          }

Output : send : msgsnd FAIL: Success


You are going to have to use a common key value between your two independent processes ... using IPC_PRIVATE means you are not planning on sharing the queue between two processes unless the secondary process has been forked from the first process. Because of the forking operation, the child will inherent the queue identifier from the parent process, so using IPC_PRVATE in that scenario is okay. But because using IPC_PRIVATE creates a unique key-value for every call its used in, for scenarios where you have two completely independent processes, such as a server/client relationship, you will need to create a common key ... it can either be a "magic number" that you share between all the processes that is already not in-use by another queue, shared memory segment, etc., or you can create a key off a common file in the filesystem by using ftok().


This question is the reason you should not use the ancient SysV message queues - there's simply no good way to get a key that's unique. Even with ftok, collisions are sufficiently likely that you must write code to try to work around them. Pretend you never saw the SysV IPC interfaces and use POSIX message queues instead; see man mq_open.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号