[英]message queue(IPC) receiving process not printing the received data in C
我正在C linux中實現IPC的消息隊列機制。 以下是我的接收流程。 它不打印收到的消息。 我認為它正在生成有效的msqid,而msgrcv函數的其他參數也正確。 為什么這樣?
//header files
#include"msgbuf.h"
int main()
{
int msqid;
key_t key;
int msgflg = 0666;
message_buf *rbuf;
rbuf=malloc(sizeof(*rbuf));
rbuf->m=malloc(sizeof(M1));
key = ftok("/home/user",12);
if ((msqid = msgget(key, msgflg)) ==-1)
{
perror("msgget");
exit(1);
}
printf("\n\n%d\n",msqid); //working fine till here.
/* Receive an answer of message type 1. */
if (msgrcv(msqid, &rbuf, sizeof(rbuf->m), 1, 0) < 0)
{
perror("msgrcv");
exit(1);
}
/* Print the answer. */
printf("Received message text= %s\n", rbuf->m->cp);
return 0;
}
現在msgbuf.h
typedef struct msgclient
{
int msglen;
int msgtype;
char *cp;
}M1;
typedef struct msgbuf1
{
long mtype;
M1 *m;
} message_buf;
if (msgrcv(msqid, &rbuf, sizeof(rbuf->m), 1, 0) < 0)
應該
if (msgrcv(msqid, &rbuf, sizeof(struct message_buf), 1, 0) < 0)
由於兩個單獨的進程具有兩個單獨的內存區域,因此沒有必要將指針傳遞給另一個進程,因為傳遞的指針(如果它在接收進程中根本指向任何東西)將不會指向它所指向的內容。原始過程。
您將需要更改char *cp;
在發送消息緩沖區之前,先將M1中的字符復制到字符數組中,然后將字符串復制到其中。 指示字符串長度的長度字節也是可取的(但不一定是必需的)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.