Steven Hsu
Steven Hsu

Reputation: 183

C - Reading an integer through shared memory with mmap

Currently I have got my shared memory working between 2 processes my parent looks like this

/* strings written to shared memory */
const char *message_0 = "Hello";
const char *message_1 = "World!";
/* shared memory file descriptor */
int shm_fd;
/* pointer to shared memory obect */
void *ptr;
/* create the shared memory object */
shm_fd = shm_open(name, O_CREAT | O_RDWR, 0666);
/* configure the size of the shared memory object */
ftruncate(shm_fd, SIZE);
/* memory map the shared memory object */
ptr = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0);
/* write to the shared memory object */
sprintf(ptr,"%s",message 0);
ptr += strlen(message_0);
sprintf(ptr,"%s",message 1);
ptr += strlen(message_1);

and my child process receives the code like so

const char *name = "OS";
/* shared memory file descriptor */
int shm_fd;
/* pointer to shared memory obect */
void *ptr;
    /* open the shared memory object */
    shm_fd = shm_open(name,O_CREAT | O_RDWR, 0666);
    /* memory map the shared memory object */
    ptr = mmap(0, SIZE, PROT_READ, MAP_SHARED, shm_fd, 0);
    /* read from the shared memory object */
    //char message = ptr;
    //int newmsg;
    //newmsg = atoi(message);
    printf("%s",(char *)ptr);
    printf("\n");

Now instead of passing hello world I would like to pass arrays instead, so I tried changing the end of my parent to try passing a single integer.

sprintf(ptr, "%d", 5);
ptr += 20; //just used 20 since it should be big enough for now

and in my child process I changed

printf("%d",(char *)ptr);

to

printf("%s", (int *)ptr);

However my message always messes up somewhere, and I print an invalid number instead. Can anyone tell me what i am missing?

Upvotes: 2

Views: 4215

Answers (1)

Marcus Müller
Marcus Müller

Reputation: 36337

You shouldn't try to represent your numeric values as strings when passing them via memory. Your receiver should just take a pointer to the address where you put your int, and interpret it as int:

child:

ptr = (int*) mmap(0, SIZE, PROT_READ, MAP_SHARED, shm_fd, 0);
....
int value = *ptr;

Upvotes: 1

Related Questions