[comp.unix.wizards] System V.2 IPC

gregg%a.cs.okstate.edu@RELAY.CS.NET (04/13/87)

Tony,

    There are 2 tricks that one can use to make use of the structure.  For
strings, the declaration in the header file works fine, because you can
allocate a msgbuf using malloc(3).  I frequently use the following code
for passing strings down message queues.  Note that I do not use this
function explicitly, but the code represents the logical sequence of
events necessary to perform the task.

    sndstr (qid, str)
        int qid;
        char *str;
    {
        struct msgbuf *msgptr;
        int size, i;

        msgptr = (struct msgptr *)
                        malloc (size = (sizeof(struct msgbuf)+strlen(str)));
        strcpy (msgptr->mtext, str);
        i = msgsnd (qid, msgptr, size, IPC_NOWAIT);
        free (msgptr);
        return (i);
    }

For structures, I use something of the form:

    sndstruct (qid, strptr)
        int qid;
        struct foo *strptr;
    {
        struct foo *newstruct;
        struct msgbuf *msgptr;
        int size, i;

        msgptr = (struct msgptr *)
            malloc (size = (sizeof (struct msgbuf) + sizeof (struct foo) - 1));

        memcpy (msgptr -> mtext, (char *) strptr, sizeof(struct foo));
        i = msgsnd (qid, msgptr, size, IPC_NOWAIT);
        free (msgptr);
        return (i);
    }

Note the "-1" above to account for the extra byte that we don't use in the
msgbuf structure.  For strings, this byte would account for the null byte at
the end of the string.  For structures, we may not really need this unless
there is a variable length string at the end of the structure, e.g.

	struct foo {
		int types[5];
		char flags[5];
		char idxs[5];
		char data[1];	/*  Variable length string.  */
	};

Hope this helps...

-----
Gregg Wonderly
Department of Computing and Information Sciences
Oklahoma State University

UUCP: {cbosgd, ea, ihnp4, isucs1, mcvax, uokvax}!okstate!gregg
ARPA:  gregg@A.CS.OKSTATE.EDU