Check if message queue exists

I create a message queue in C as follows:

int msgid; 
int msgflg = IPC_CREAT | 0666;

key_t key;

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

How to check if a queue exists? And I do not want to create a new one if it already exists.

+4
source share
1 answer

Pass the flag IPC_EXCLto msgget(), and if it doesn't work as errnowell 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");
  }
}
+4
source

Source: https://habr.com/ru/post/1538872/


All Articles