c - C 中使用共享内存的 IPC

标签 c linux ipc shared-memory

我正在 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/

相关文章:

c - 接收一个字符并输出其 ASCII 十六进制值

使用指针复制字符串而不使用 strcpy

c - 如何在C中找到数字中的最小数字及其在 vector 中的位置?

linux - 尝试并行启动任务的 Shell 脚本?

c++ - 如何连接两个程序(c++、qt)

c - 在 C 中实现链表时,谁负责释放值?

python - 根据 Linux 文件系统层次结构标准,放置 Python 虚拟环境的正确位置在哪里?

java - 现代 linux 中 linux 关机/注销 TERM 信号处理程序的时间容差是多少?

c# - C# 应用程序与 C++ 和 VB.Net 中的其他应用程序之间的 IPC

Python进程间通信建议