0

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.

3
  • Do you have any reason to expect the IDs to be monotonically increasing, or reused, that comes from a better source than "somewhere"? Commented Aug 8, 2024 at 17:20
  • I take statement back. The source is not reliable. Commented Aug 9, 2024 at 6:22
  • I now speculate that the id is assigned as 1+the highest assigned id. Also, the jump can be due to the fact the those ids are reserved for the system functioning. However, the id destroyed before new message queue is created. Commented Aug 9, 2024 at 6:26

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.