Getting wrong message using msgrcv and msgsnd commands in c

Consider the following program:

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/errno.h>
#include <signal.h>

typedef struct msg{
    long mtype;
}msg;

void child1();
void child2();
int queue_ids[2];
pid_t pid1;
pid_t pid2;

int main(){

    for (int i=0; i<2; i++){
        key_t key = 2023+i;
        queue_ids[i] = msgget(key, IPC_CREAT | 0666);
    }


    if( (pid1 = fork()) == 0)
        child1();
    if( (pid2 = fork()) == 0)
        child2();

    printf("SHould see 2 of those");
    sleep(50);

}

void child1(){

    msg msnd;
    msnd.mtype = 150;
    msgsnd(queue_ids[1], &msnd, sizeof(msg), 0);
    printf("child1 sent a message\n");
    sleep(450);
}

void child2(){
    sleep(10);
    msg *mrcv = (msg*) malloc(sizeof(msg));
    msgrcv(queue_ids[1],mrcv, sizeof(msg),0,0);
    printf("child2 recieved message. mtype = %ld\n", mrcv->mtype);
    kill(pid1, SIGKILL);
}

I tried to simply cummunicate between 2 processes. As I understand, using msgrcv with argument of msgtype = 0 should just read the first message in the queue. Since child1 is the only one that sends messages to the queue, I expect to just read his message with mtype=150 as soon as it will be sent. But my output is the following:

child1 seng a message
child2 recieved message. mtype = 94063516914727

What can cause the problem?

Also, in child2, I tried to replace msg *mrcv = (msg*) malloc(sizeof(msg)); with simplt msg mrcv; and then the call will be:

msgrcv(queue_ids[1], &mrcv, sizeof(msg),0,0);

But I got another error

*** stack smashing detected ***: terminated

Why is that? when I declare msg mrcv; shouldnt the same amount of memory be allocated as when I am using malloc with sizeof(msg) ?

Any help would be highly appreciated. Thanks in advance.

Upvotes: 0

Views: 154

Answers (0)

Related Questions