Search code examples
clinuxipcshared-memory

IPC using shared memory in C


I am implementing IPC using shared memory in C linux. Here is my receiving process. It's receiving correct length but not the message. However sending process is properly sending it. Please see this and let me know the error.

//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 is

typedef struct msgbuf1
{
    int msglen;
    char *cp;
}message_buf;

thanks :)


Solution

  • You read a char* from the shared memory region. However, that points to a buffer allocated with malloc, in the remote process. As such it points to the process heap of local to that other process.

    This is simply undefined behaviour.

    Instead, make the character buffer part of the shared memory data structure:

    //header files
    #define MAX_SH_BUFSIZE 1024
    //
    typedef struct msgbuf1
    {
        int msglen;
        char cp[MAX_SH_BUFSIZE];
    } message_buf;