bluegenetic
bluegenetic

Reputation: 1435

Message queue msgsnd mtext field

When using msgsnd the structure mentioned in man page is

 struct mymsg {
     long mtype;    /* message type */
     char mtext[1]; /* body of message */
 };

But if you use it like

func(char *array, int sizeofarray)
{
     struct mymsg {
         long mtype;    /* message type */
         char *ptr; /* body of message */
     };

    msgq.mtype = 1;
    msgq.ptr = array;

    msgsnd(msqid, &msgq, sizeofarray, 0);
}

Assign ptr to some local array[200] (array could be got as a parameter in function), the message received on the other side is junk. Why is this?

Upvotes: 0

Views: 1040

Answers (2)

caf
caf

Reputation: 239071

It's junk because the structure you have specified is not of the form that msgsnd wants. It expects the data to be copied to immediately follow the mtype value in memory, not be in an array somewhere else.

If you want to send an array of length 200, you need to do something like:

struct mymsg {
    long mtype;
    char mtext[200];
} foo;

foo.mtype = 1;
memcpy(foo.mtext, array, 200);

msgsnd(msqid, &foo, 200, 0);

Upvotes: 2

Duck
Duck

Reputation: 27552

Even if this wasn't wrong for the reasons caf points out, let's say you did something like:

func(char *array)
{
     struct mymsg 
     {
         long mtype;    /* message type */
         char *ptr; /* body of message */
     };

    msgq.mtype = 1;
    msgq.ptr = array;

    msgsnd(msqid, &msgq, sizeof(ptr), 0);
}

If a different process is reading the queue, what would ptr mean to it? What would it point to, if anything, in a different address space?

Upvotes: 0

Related Questions