code_junkie

Reading Other Process' Memory in OS X / BSD

Nov 10th, 2011
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. // Create shared memory block
  2. void* sharedMemory = NULL;
  3. size_t shmemSize = 123456;
  4. const char* shmName = "mySharedMemPath";
  5. int shFD = shm_open(shmName, (O_CREAT | O_EXCL | O_RDWR), 0600);
  6. if (shFD >= 0) {
  7. if (ftruncate(shFD, shmemSize) == 0) {
  8. sharedMemory = mmap(NULL, shmemSize, (PROT_READ | PROT_WRITE), MAP_SHARED, shFD, 0);
  9. if (sharedMemory != MAP_FAILED) {
  10. // Initialize shared memory if needed
  11. // Send 'shmemSize' & 'shmemSize' to other process(es)
  12. } else handle error
  13. } else handle error
  14. close(shFD); // Note: sharedMemory still valid until munmap() called
  15. } else handle error
  16.  
  17. ...
  18. Do stuff with shared memory
  19. ...
  20.  
  21. // Tear down shared memory
  22. if (sharedMemory != NULL) munmap(sharedMemory, shmemSize);
  23. if (shFD >= 0) shm_unlink(shmName);
  24.  
  25.  
  26.  
  27.  
  28.  
  29. // Get the shared memory block from another process
  30. void* sharedMemory = NULL;
  31. size_t shmemSize = 123456; // Or fetched via some other form of IPC
  32. const char* shmName = "mySharedMemPath";// Or fetched via some other form of IPC
  33. int shFD = shm_open(shmName, (O_RDONLY), 0600); // Can be R/W if you want
  34. if (shFD >= 0) {
  35. data = mmap(NULL, shmemSize, PROT_READ, MAP_SHARED, shFD, 0);
  36. if (data != MAP_FAILED) {
  37. // Check shared memory for validity
  38. } else handle error
  39. close(shFD); // Note: sharedMemory still valid until munmap() called
  40. } else handle error
  41.  
  42.  
  43. ...
  44. Do stuff with shared memory
  45. ...
  46.  
  47. // Tear down shared memory
  48. if (sharedMemory != NULL) munmap(sharedMemory, shmemSize);
  49. // Only the creator should shm_unlink()
Add Comment
Please, Sign In to add comment