2

我正在使用 msgget() 系统调用来获取新的 msg 队列。我在其中使用了 IPC_CREAT 和 IPC_EXCL 标志。就像 message_queue = msgget(ftok("/tmp", 100), (0666 | IPC_CREAT | IPC_EXCL)); 现在,当我的 prog 意外存在时,味精队列仍然存在,我无法重新创建味精队列。所以,我的问题是“我怎样才能取回现有的 msg 队列的 ID?”

顺便说一句, msg queue 将其 id 存储在哪里?

4

3 回答 3

2

Regd "我怎样才能取回现有的 msg 队列的 ID?"

来自 man msgget

   If  msgflg  specifies both IPC_CREAT and IPC_EXCL and a message queue already exists for key, then msgget() fails with errno set to EEX-
   IST.  (This is analogous to the effect of the combination O_CREAT | O_EXCL for open(2).)

尝试不使用 IPC_EXCL 标志。

注册。msg queue在哪里存储它的id

从人 proc

   /proc/sysvipc
          Subdirectory  containing  the  pseudo-files  msg,  sem  and  shm.  These files list the System V Interprocess Communication (IPC)
          objects (respectively: message queues, semaphores, and shared memory) that currently  exist  on  the  system,  providing  similar
          information  to that available via ipcs(1).  These files have headers and are formatted (one IPC object per line) for easy under-
          standing.  svipc(7) provides further background on the information shown by these files.
于 2012-04-05T07:43:48.423 回答
1

下面是一个尝试回答这个问题,如果有用的话,功劳应该去The Linux Programmer's Guide。如果它被确定为无关紧要或什么的,错误都是我的。

ipcs 命令可用于获取所有 System V IPC 对象的状态。

ipcs -q: Show only message queues
ipcs -s: Show only semaphores
ipcs -m: Show only shared memory
ipcs --help: Additional arguments

ipcrm 命令可用于从内核中删除 IPC 对象。虽然 IPC 对象可以通过用户代码中的系统调用来删除(我们稍后会看到如何),但经常需要手动删除 IPC 对象,尤其是在开发环境中。

它的用法很简单:

ipcrm <msg | sem | shm> <IPC ID>
于 2012-09-18T17:10:13.320 回答
0

不要尝试第二次重新创建消息队列。您IPC_CREAT | IPC_EXCL第二次的使用导致msgget失败。

来自msgget的手册页

如果msgflg同时指定了IPC_CREATIPC_EXCL并且 key 的消息队列已经存在,那么msgget () 将失败并且errno设置为EEXIST。(这类似于组合O_CREAT | O_EXCLopen (2) 的影响。)

所以你仍然可以继续使用msgget第二次,但只使用IPC_CREAT标志。还要注意检查两者的返回值,ftok并将msgget错误值(如果有)与手册页进行比较。还要检查errno

此外,如果您对现有消息队列有太多问题,您可以通过调用msgctl标志IPC_RMID来删除它

此外,关于味精队列存储位置的另一个答案。您可能很想删除一个麻烦的消息队列 :) 但请注意,它们是位于虚拟文件系统 /proc 上的只读文件!

于 2012-04-05T07:40:43.570 回答