2

I try to use shared memory with shm_open and mmap. However, whenever I try to write to that memory, I get bus error. The minimalist example code is given below. What is the problem here and how can it be solved?

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

// compile with -lrt

char fname[64];
int fd;

int main()
{
    int * sm;
    sprintf( fname, "%d_%u", 4, 4 ); 

    if ((fd = shm_open(fname, O_CREAT | O_RDWR, 0777)) == -1)
    {        
        perror(NULL);
        return 0;
    }
    sm = (int*)mmap(0, (size_t)4096, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED, 
      fd, 0);
    printf( "Now trying to see if it works!\n" );
    sm[0] = 42;
    printf( "%d, %d!\n", sm[0], sm[1] );

    return 0;
}

The output I get is the following

Now trying to see if it works!
Bus error
pythonic
  • 20,589
  • 43
  • 136
  • 219
  • 2
    You need to check if `mmap` returns `MAP_FAILED` and, if so, consult `errno` to figure out why. (Also, you wouldn't be trying to write to a zero-length shared object, would you? Neither `mmap`, nor a write to an `mmap` area, can enlarge an object.) – David Schwartz Jul 22 '12 at 13:03
  • 1
    Related: http://stackoverflow.com/questions/212466/what-is-a-bus-error – Ciro Santilli OurBigBook.com Aug 07 '15 at 12:03

1 Answers1

6

A newly-created object has a size of zero. You cannot change the size of an object by mapping it or writing to its mapping. You probably need to call ftruncate before mmap. (If your code had error-checking, this would be much easier to figure out.)

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • In this case error checking doesn't matter as mmap will happily map a zero length file, as long as length is page aligned. – sergio91pt Apr 30 '13 at 21:07