Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use shm_open with mmap properly

I am trying to create a shared memory area using examples and documentation I found online. My goal is IPC , so I can make different processes talk to each other.

This my C file

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <errno.h>

int main (int argc, char *argv[])
{

struct stat sb;
off_t len;
char *p;
int fd;

fd = shm_open("test",  O_RDWR | O_CREAT); //,S_IRUSR | S_IWUSR);

if (fd == -1) {
    perror("open");
    return 1;
}

if (fstat(fd, &sb)==-1){
    perror("fstat");
    return 1;
}

/*if (!S_ISREG(sb.st_mode)){
    fprintf(stderr, "%s is not a file\n",fileName);
    return 1;
}*/

p = mmap(0, sb.st_size, PROT_WRITE, MAP_SHARED, fd, 0);
if (p == MAP_FAILED){
    perror("mmap");


    return 1;

}

if (close(fd)==-1) {
    perror("close");
    return 1;

}
for (len = 0; len < sb.st_size; len++) {
    putchar(p[len]);

}

if (munmap(p, sb.st_size) == -1) {
    perror("munmao");
    return 1;
}
fprintf(stderr,"\n");
return 0;
}

The problem is that I am getting a mmap: Invalid argument. I assume something is wrong with fd but have no clue how to fix it, any help would be appreciated. I am on Yosemite using latest XCODE .

like image 966
Kilon Avatar asked Nov 09 '22 21:11

Kilon


1 Answers

You need to extend the size of the shared memory mapping, at least the first time when you create it. Right now its size is 0, and mmap is not going to allow you to make a zero length mapping.

So instead of your fstat() call, do e.g.:

size_t len = 4096;
if (ftruncate(fd, len) == -1) {
    perror("ftruncate");
    return 1;
}

And pass this len to mmap().

like image 156
nos Avatar answered Nov 14 '22 22:11

nos