简体   繁体   中英

C program IPC message

I am using IPC for 2 programs communication.

Snippet of my code for sender:

int msgflg = IPC_CREAT | 0666;  
key_t key_id;  
struct msgbuf sbuf;  
size_t buflen;  
key_id = 1235;  

sbuf.mtype = 1;  

if (msgsnd(msqid, &sbuf, buflen, IPC_NOWAIT) < 0)  
{               die("msgsnd");  

}  
else {
    mvprintw(8, 0, "%s", "                  ");
    mvprintw(8, 0, "%s", sbuf.mtext);           
}

Receiving end:

if ((msqid = msgget(key_id, 0666)) < 0)  
   die("msgget()");         //break;

//Receive an answer of message type 1.  

if (msgrcv(msqid, &rcvbuffer, MAXSIZE, 1, 0) < 0)  
    die("msgrcv");  
mvprintw(curr_row + 1, 0, "Cleaning process monitor: %s", rcvbuffer.mtext);

The communication is working perfect but the message received at receiver's end is not fully received.

If i am sending "Hello" it receives only "H" My buffer size is 200

You can't declare struct msgbuf directly with mtext size 1

struct msgbuf {
    long mtype;       /* message type, must be > 0 */
    char mtext[1];    /* message data */ 
};

What you need to do is to declare a long char array in your structure, and then convert it to void*

For example,

struct msgbuf {
    long type;
    char mtext[200];
};

struct msgbuf mybuf;
// set type, store data in mtext

msgsnd(msqid, (void*)&mybuf, sizeof(msgbuf)+1, IPC_NOWAIT)  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM