0

I am learning message queues, wrote code to create message queue

#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <stdlib.h>
#include <errno.h>

int main()
{
    key_t key;
    int msgid;

    key = ftok("proj", 64);
    if (key == -1) {
        perror("ftok failed");
        exit(1);
    }
    printf("key:%x\n", key);
    //IPC_CREAT: creating message queue if not exists
    msgid = msgget(key, IPC_CREAT);
    if (msgid == -1) {
        perror("msgget failed");
        printf("errno:%d\n", errno);
        if (errno == ENOENT)
            printf("No message queue exists for key and msgflg did not specify IPC_CREAT\n");
        exit(2);
    }
    printf("msgid:%x\n", msgid);


    return 0;
}

Running the command did not show output: ipcs -q

panther2@ubuntu:~/c_codes/msg_queue$ ipcs -q

------ Message Queues --------
key        msqid      owner      perms      used-bytes   messages    

Can you guys please tell me if i am making any mistake

1 Answer 1

1

As I see there is nothing wrong with your code, but the behavior is really strange, even on my system.

As mssget returns 0, everything is ok ( it should return a non negative number which 0 is ) and the queue can be used.

I added a for(;;); at the end of your prog and start it again. ipcs now shows:

0x4025077b 0 krud 0 0 0

After I ipcrm -q 0 and start the program again, I got a new id for each run. I now removed the endless loop and all and everything still works, every run I got a message queue with different number which I always have to destroy before next run.

That is really strange!

I found a lot reports on that topic, e.g.: https://www.unix.com/programming/248572-msgget-2-returns-0-workaround-fix.html http://forums.codeguru.com/showthread.php?403036-strange-problem-in-using-msgget%28%29-in-Linux

Keep us informed if you have found a valid solution!

As my system now generates at every run a new message queue with a id > 0, I can't reproduce this behavior anymore. I did not want to reboot again ;)

Sign up to request clarification or add additional context in comments.

Comments

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.