c - How can I share existing memory with shm_open? -


In Linux, I want to share some of my memory content with other processes. One way of doing this is by using 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", serrerer (wrong)); Return EXIT_FAILURE; } / * Set the size of the memory object * / if (FTNcT (FD, Sizef (* Eder)) == -1) {FPrint F (Stader, "FTRCNCT:% S \ n", Strayer (wrong)); Return EXIT_FAILURE; } / * 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 can not share "allocated memory" beforehand. My question is whether I can share the previous allotted memory contents without allocating again I am

Thank you in advance.

Your code shares the memory, but both of your processes will be found in different address fields. . If you want the same area, the addr value will be the same. In this case you can create objects in this memory, use internal pointers and your object will be visible in both legitimate and in both processes.

There are two ways that you can do this.

1) Fork () to make another process

2) Ask the mmap to assign memory

Number two Your code looks for:

  / * Create a new memory object * / fd = shm_open ("/ bolts", O_RDWR | O_CREAT, 0777); If (FD == -1) {fprintf (stderr, "Open failed:% s \ n", serrere (wrong)); Return EXIT_FAILURE; } / * Set the size of the memory object * / if (FTNcT (FD, Sizef (* Eder)) == -1) {FPrint F (Stader, "FTRCNCT:% S \ n", Strayer (wrong)); Return EXIT_FAILURE; } // You know the basis for the memory area that you want to share. // Choose it carefully, both processes should be available to you! Zero * baseAddr = 0x7fff00000000; / * Map the memory object * / ADR = MMAP (baseadder, size (* adr), prosprade | 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; }  


Comments

Popular posts from this blog

ios - How do I use CFArrayRef in Swift? -

eclipse plugin - Run java code error: Workspace is closed -

c - Error on building source code in VC 6 -