我正在 C linux 中使用共享内存实现 IPC。这是我的接收过程。它接收到正确的长度,但没有接收到消息。但是发送过程正在正确发送它。 请查看此内容并告诉我错误。
//header files
#include "/home/user/msgbuf.h"
#define SHMSZ 127
int main()
{
int shmid;
key_t key;
message_buf *rbuf;
rbuf=malloc(sizeof(*rbuf));
key = ftok("/home/user/shmem",17);
if ((shmid = shmget(key, SHMSZ, 0666)) < 0)
{ perror("shmget");
exit(1);
}
printf("\nShared Memory Id = %d\n",shmid);
if ((rbuf = shmat(shmid, NULL, 0)) == (message_buf *) -1)
{ perror("shmat");
exit(1);
}
printf("\nMEMORY SEGMENT ATTACHED TO THE CLIENT'S PROCESS\n");
/* Now read what the server put in the memory */
printf("\nmsglen = %d",rbuf->msglen); //this is correct
rbuf->cp=malloc(rbuf->msglen);
memcpy(&rbuf->cp,rbuf+sizeof(int),sizeof(*rbuf));
printf("\nMESSAGE :: %s",rbuf->cp); //MESSAGE :: null
fflush(stdout);
shmdt(&shmid);
printf("\nMEMORY SEGMENT %d DETACHED\n",shmid);
return 0;
}
msgbuf.h 是
typedef struct msgbuf1
{
int msglen;
char *cp;
}message_buf;
谢谢:)
最佳答案
您从共享内存区域读取了一个 char*。然而,它指向远程进程中用 malloc 分配的缓冲区。因此,它指向该其他进程的本地进程堆。
这只是未定义的行为。
相反,使字符缓冲区成为共享内存数据结构的一部分:
//header files
#define MAX_SH_BUFSIZE 1024
//
typedef struct msgbuf1
{
int msglen;
char cp[MAX_SH_BUFSIZE];
} message_buf;
关于c - C 中使用共享内存的 IPC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22760184/