Member Avatar

Hey, so i'm having some problems with my message passing code.
Ultimately, what i'm trying to do is use the msgget/snd/rcv commands to send the pid of the parent to the child, and visa versa. However, i'm getting an invalid argument error fr my msgsnd in the child process. My code is a bit messy, but here's what I have:

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

int main(void)
    struct msgbuf {
        long priority;
        int temp;
        int pid;
    } buf;
    int msqid, result;
    pid_t pid, myPid;
    size_t size = sizeof(buf);

    msqid = msgget(2345, 0600|IPC_CREAT); //create message sending
    printf("msqid: %d\n", msqid);      
    pid = fork();
    switch (pid) {
        case -1:
            printf("fork failed");
        case 0: 
                //msqid = msgget(key, 0600|IPC_CREAT); //create message sending
                //printf("%d\n", msqid);
            myPid = getpid();
   = myPid;
            printf("pid child/sender:%d\n... Sending\n",;
            result = msgsnd(msqid, &buf, sizeof(buf)-sizeof(long), 0); //Send process id
            if (result==-1) {
                //wait(NULL); //wait for child to finish sending pid back
            result = msgrcv(msqid, &buf, sizeof(buf)-sizeof(long), 2, 0);
            if (result==-1) {
            printf("Received reply from: %d\n",;

                //msqid = msgget(key, 0666|IPC_CREAT); //create message sending
                //printf("%d\n", msqid);
            printf("pid parent/receiver: %d\n... Receiving\n", getpid());
            msgrcv(msqid, &buf, sizeof(buf)-sizeof(long), 2, 0);
            printf("Serving for sender: %d\n",;
   = getpid();
            msgsnd(msqid, &buf, sizeof(buf)-sizeof(long), 0); //Send process id
        //struct msqid_ds dummyParam;
    msgctl(msqid, IPC_RMID, 0);


Any idea on what's going on? My output is:
msqid: 65536
pid parent/receiver: 1200
... Receiving
pid child/sender:1203
... Sending
msgsnd:: Invalid argument
Serving for sender: 0

I was outputting the msqid to make sure that the child and parent were connected to the same memory

Recommended Answers

All 3 Replies

You didn't initialize buf.priority (mtype in the msgsnd terms). msgsnd requires it to be positive, thus EINVAL. Adding

buf.priority = 2;

at around line 43 heals everything.
PS: Why 2? Because of 2 at line 76...

Member Avatar

Thanks man. I had a few other problems with ordering, but it's all working.

sir ? wat does msqid mean >? because the program when i try it, it does RUN.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.