How can I share existing memory with shm_open?

On Linux, I want to share some of the memory contents of my process with other processes. one way to do this is to use shm_open and mmap. as shown below.

/* Create a new memory object */ fd = shm_open( "/bolts", O_RDWR | O_CREAT, 0777 ); if( fd == -1 ) { fprintf( stderr, "Open failed:%s\n", strerror( errno ) ); return EXIT_FAILURE; } /* Set the memory object size */ if( ftruncate( fd, sizeof( *addr ) ) == -1 ) { fprintf( stderr, "ftruncate: %s\n", strerror( errno ) ); return EXIT_FAILURE; } /* Map the memory object */ addr = mmap( 0, sizeof( *addr ), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0 ); if( addr == MAP_FAILED ) { fprintf( stderr, "mmap failed: %s\n", strerror( errno ) ); return EXIT_FAILURE; } 

However, in this way, I cannot share the β€œalready allocated memory”. my question is: can I share the previously allocated memory contents without redistributing them?

thank you in advance.

+8
source share
1 answer

Your code does share memory, but both of your processes will get different address areas. You want to have the same region, so the value of addr will be the same. In this case, you can create objects in this memory, use internal pointers, and your objects will be real and visible in both processes.

There are two ways you can do this.

1) make fork () to create another process

2) ask mmap to allocate memory at the special address MAP_FIXED .

For the second number your code will look:

 /* Create a new memory object */ fd = shm_open( "/bolts", O_RDWR | O_CREAT, 0777 ); if( fd == -1 ) { fprintf( stderr, "Open failed:%s\n", strerror( errno ) ); return EXIT_FAILURE; } /* Set the memory object size */ if( ftruncate( fd, sizeof( *addr ) ) == -1 ) { fprintf( stderr, "ftruncate: %s\n", strerror( errno ) ); return EXIT_FAILURE; } // You base address for memory region that you want to share. // Choose this carefully, you both processes MUST have it available! void * baseAddr = 0x7fff00000000; /* Map the memory object */ addr = mmap( baseAddr, sizeof( *addr ), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, fd, 0 ); if( addr == MAP_FAILED | MAP_FIXED ) { fprintf( stderr, "mmap failed: %s\n", strerror( errno ) ); return EXIT_FAILURE; } 

image

+2
source

Source: https://habr.com/ru/post/1241928/


All Articles