I create a message queue in C like this:

int msgid; 
int msgflg = IPC_CREAT | 0666;

key_t key;

key = ftok(".",'a'); 
if ((msgid = msgget(key,msgflg)) < 0 ){
    syserr("msgget error");
}

How can I check if the queue already exists? And I don't want to create a new if already exists.

有帮助吗?

解决方案

Pass the flag IPC_EXCL to msgget() and if it fails and errno equals EEXIST then the queue exists.

int msgid = -1;
key_t key = -1;

if (-1 == (key = ftok(".", 'a')))
{
  perror("ftok() failed");
} 
else if (-1 == (msgid = msgget(key, IPC_EXCL | IPC_CREAT | 0666)))
{
  if (EEXIST == errno)
  {
     fprintf(stderr, "The queue exists.\n");
  }
  else
  {
    perror("msgget() failed");
  }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top