0

I am trying to use multiple different message queues in C for communicating between different processes on Linux. I use systemd.

See my code below for one process. Why is it that msgid1 and msgid2 are the exact same value in this case?

Doesn't this then mean that the queues are the same?

I would expect that I am creating different queues here.

#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/msg.h>

int main()
{
    struct buffer1
    {
        long mesg_type;
        int num;
    }message1;

    struct buffer2
    {
        long mesg_type;
        char text[20];
    }message2;

    key_t key1;
    key_t key2;

    int msgid1;
    int msgid2;

    // ftok to generate unique key
    key1 = ftok("test1",1);
    key2 = ftok("test2",2);

    msgid1 = msgget(key1, 0666 | IPC_CREAT);
    msgid2 = msgget(key2, 0666 | IPC_CREAT);

    // printf("%d  %d", msgid1 , msgid2 ); -- msgid1  and msgid2 are the same values

    //msgrcv(msgid1, &message1, sizeof(message1), 1, 0);
    //msgrcv(msgid2, &message2, sizeof(message2), 1, 0);
}

EDIT : I have removed the error checking on function calls here for simplicity. There are no errors in this case.

Engineer999
  • 3,683
  • 6
  • 33
  • 71
  • https://stackoverflow.com/editing-help – Yunnosch Mar 25 '22 at 09:36
  • What about `key1` and `key2`, or they also identical? Please make a [mre] which demonstrates and provide sample output. – Yunnosch Mar 25 '22 at 09:37
  • 1
    You should include checking to see if `ftok()` and `msgget()` and other functions return errors. – Shawn Mar 25 '22 at 09:39
  • @Shawn I am checking for errors. There are none. I just want to remove them from the program here for simplicity. – Engineer999 Mar 25 '22 at 10:07
  • 1
    I copied your code, and got `key1 = key2 = -1`, with `errno = No such file or directory`. Then I created `touch test1 test2` and uncommented the `printf`, and run again - it outputted `0 1` for `msgid1, msgid2`. I cannot reproduce. – KamilCuk Mar 25 '22 at 10:17
  • @KamilCuk Thanks. What system are you running on? – Engineer999 Mar 25 '22 at 16:06
  • `What system are you running on?` Archlinux linux5.16.15-zen1 gcc11.2.0 glibc2.35 – KamilCuk Mar 25 '22 at 18:45

0 Answers0