views:

42

answers:

2

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?

+2  A: 

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, &msgq, 200, 0);
caf
A: 

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?

Duck
It is not sizeof(ptr) but size of original array. Anyways.. I already guessed the answer which caf replied. I just confirmed.
bluegenetic
I know. You missed the point. I trying to demonstrate something else.
Duck
Thank you very much :)
bluegenetic