[Solved] how to send an integer via message queue?

how can i send an integer via message queue?
i try this, but it doesn't work, child process receive 13345943 instead of 5

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/msg.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <errno.h>
#include <unistd.h>
#include <wait.h>
#include <mqueue.h>
#define SEMPERM 0600

typedef union _semun {
    int val;
    struct semid_ds *buf;
    unsigned short *array;
}semun;
int initsem (key_t semkey){
    int status=0, semid;
    semid=semget(semkey, 1 , SEMPERM | IPC_CREAT | IPC_EXCL);
    if (semid==-1){
        if (errno==EEXIST){semid=semget(semkey,1,0);}
    } else {
        semun arg;
        arg.val=0;
        status=semctl(semid,0,SETVAL,arg);
    }
    if ((semid==-1) || (status==-1)){
        perror("initsem fallita");
        return (-1);
    }
    return (semid);
}
int waitSem(int semid){
    struct sembuf wait_buf;
    wait_buf.sem_num=0;
    wait_buf.sem_op=1;
    wait_buf.sem_flg=SEM_UNDO;
    if (semop(semid,&wait_buf, 1)==-1){
        perror("waitSem Fallita");
        exit(-1);
    }
    return 0;
}

int signalSem (int semid){
    struct sembuf signal_buf;
    signal_buf.sem_num=0;
    signal_buf.sem_op=1;
    signal_buf.sem_flg=SEM_UNDO;
    if (semop(semid,&signal_buf,1)==-1){
        perror("signalSem fallita");
        exit(1);
    }
    return 0;
}
int main(){
    pid_t child;
    key_t keymsg=33;
    int id,retval;
    struct my_msg{
        long mtype;
        int mint;
    }message,receive;
    id=msgget(keymsg,0777|IPC_CREAT);
    if (id<0){
        perror("error created queue main");
        exit(-1);
    }
    int a=5;
    message.mtype=1;
    message.mint=a;
    retval=msgsnd(id,&message,1,0);
    if(retval<0){
        perror("error send main");
        exit(-1);
    }
    child=fork();
    if(child<0){
        perror("Error fork");
        exit(-1);
    }
    else if(child==0){
        int retval2,ad,b;
        ad=msgget(keymsg,0777|IPC_CREAT);
        if(ad<0){
            perror("Error created queue");
            exit(-1);
        }
        retval2=msgrcv(ad,&receive,1,1,0777);
        b=receive.mint;
        if (retval2<0){
            perror("error rcv msg");
            exit(-1);
        }
        printf("\nb= %d\n",b);
        exit(0);
    }
    if((retval=msgctl(id,IPC_RMID,NULL))==-1){
            perror("error remove queue");
            exit(-1);
        }
    return 0;
}

One mistake I notice straight-off is:

retval2=msgrcv(ad,&receive,1,1,0777);

The size parameter is in bytes, so it should be sizeof(receive) - your current code allows only a single byte to be received.

1 Like

thanks a lot now it works very well