如何获取现有的msg队列ID

时间:2012-04-05 07:19:15

标签: c linux unix

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

顺便说一句,msg队列在哪里存储它的id?

3 个答案:

答案 0 :(得分: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标志。

REGD。 msg队列在哪里存储其id

来自man 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.

答案 1 :(得分: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>

答案 2 :(得分:0)

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

来自msgget

的手册页
  

如果 msgflg 指定 IPC_CREAT IPC_EXCL 以及消息队列   已经存在密钥,然后 msgget ()失败, errno 设置为 EEXIST 。   (这类似于组合 O_CREAT | O_EXCL 的效果   打开(2)。)

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

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

另外,关于msg队列存储位置的另一个答案。你很想删除令人不安的msg队列:)但请注意,它们只是在虚拟文件系统/ proc上的只读文件!

相关问题