I recently came across this topic while going through Advanced Programming in Unix Environment about IPC using message queues. I implemented a simple program that creates and deletes queues 5 times in 1st loop and in 2nd one also sends a message. I ran it a couple of times. I noticed that after id is incremented to 63. It jumps to some larger value in 3000s. From there, it jumps to 6000s and so forth.
#include <stdio.h>
#include <sys/msg.h>
#include <sys/ipc.h>
struct mymesg
{
long mtype; /* positive message type */
char mtext[512]; /* message data, of length nbytes */
};
int main()
{
int key = 65;
for (int i = 0; i < 5; i++)
{
key_t key = ftok("reffile", key + i);
if (key == -1)
{
perror("ftok");
return -1;
}
int msg_id = msgget(key, 0666 | IPC_CREAT);
if (msg_id < 0)
{
perror("msgget");
return -1;
}
printf("[%d] Message Queue ID: %d\n", i, msg_id);
msgctl(msg_id, IPC_RMID, NULL);
}
struct mymesg msg = {1, "Hello\n"};
struct msqid_ds msg_data;
key += 5;
for (int i = 0; i < 5; i++)
{
int msg_id = msgget(IPC_PRIVATE, 0666);
if (msg_id < 0)
{
perror("msgget");
return -1;
}
printf("[%d] Message Queue ID: %d\n", i, msg_id);
msgctl(msg_id, IPC_STAT, &msg_data);
printf("Queue number originally: %d\n", msg_data.msg_qnum);
if (msgsnd(msg_id, &msg, sizeof(msg), 0) < 0)
{
perror("msgsnd");
return -1;
}
msgctl(msg_id, IPC_STAT, &msg_data);
printf("Queue number incremented: %d\n", msg_data.msg_qnum);
msgctl(msg_id, IPC_RMID, NULL);
}
return 0;
}
I tried using ipcs to see the queues that might not have been destroyed but found none. I want to know why there is a gap in the ids in the first place and also why aren't the previously deleted ids being used( I read somewhere that it assigns the least positive value). I searched for hours but did not get any concrete answer.