POSIX shared memory usage and code examples for Linux interprocess communication

Source: Internet
Author: User
Tags mutex posix semaphore

POSIX shared memory has two ways of sharing memory between non-affinity processes:
1). Use a memory-mapped file, opened by the Open function, and the MMAP function maps the returned file descriptor to a file in the current process space.

2). Using the Shared Memory Area object, a Posix IPC name is opened by Shm_open. The returned descriptor is then mapped by mmap to the address space of the current process.

POSIX shared memory-related function header files and prototypes:
#include <sys/mman.h>
int Shm_open (const char *name, int oflag, mode_t mode);
Function: Open a shared memory object, get the descriptor
Return value: Successfully returned non-negative descriptor, error returned-1
Parameters: Name is the POSIX IPC name, the Oflag parameter is o_rdonly or O_RDWR, and it can be o_creat,o_excl,o_trunc when the specified O_RDWR and o_trunc are truncated to length 0 when the shared memory object already exists; Mode is the specified permission bit, which is used when o_creat is specified, and must be set to 0 without o_creat.


int Shm_unlink (const char *name);
Function: Deletes the name of a shared memory area object.
Return value: Successfully returned 0, error returned-1.


void *mmap (void *addr, size_t len, int prot, int flags, int fd, off_t offset);
Function: Maps a shared Memory object opened by Shm_open to the process address space.
Return value: Returns the start address of the mapping area if successful, and returns an error map_failed.
Parameters: addr Specifies the starting address of the process space to be mapped to, which is generally set to null pointer nulls, which is automatically assigned, and Len is the number of bytes mapped to the address space, starting with the first offset byte of the file header, and general offset set to 0;prot can be prot_read ( readable), prot_write (writable), prot_exec (executable), Prot_none (inaccessible), flags can be map_shared,map_private,map_fixed, where map_shared or MAP_ Private must specify one, map_fixed is not generally specified, and addr is a null pointer, which indicates that the address is automatically assigned to facilitate portability.

int Munmap (void *addr, size_t len);
Function: Delete the mapping relationship of the process address space
Return value: Successfully returned 0, error returned-1


int Msync (void *addr, size_t len, int flags);
Function: The content of the file is consistent with the content in the memory map area.
Return value: Successfully returned 0, error returned-1.
Parameters: Flags have 3 types, Ms_async (asynchronous Write), Ms_sync (synchronous write), ms_invalidate (invalidates cached data).

code example SHM_TEST.C, parent-child process operation shared memory area variable count plus 1, and signal volume SEM do synchronization

  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <sys/mman.h>
  4. #include <semaphore.h>
  5. #include <fcntl.h>
  6. #define MYFILE "./shm_test_file"
  7. #define SEM_NAME "/mysem"
  8. #define MYSHM "/myshm"
  9. #define TIMES 5
  10. #define USE_SHM_OPEN 0
  11. #define Sem_in_sharememory 0
  12. #if sem_in_sharememory
  13. struct shared
  14. {
  15. Sem_t Mutex;
  16. int count;
  17. }shared;
  18. #endif
  19. int main (void)
  20. {
  21. int fd,i,zero=0;
  22. #if sem_in_sharememory
  23. struct shared *ptr;
  24. #if Use_shm_open
  25. Fd=shm_open (myshm,o_rdwr| o_creat,0666);
  26. #else
  27. Fd=open (myfile,o_rdwr| o_creat,0666);
  28. #endif
  29. Write (fd,&shared,sizeof (struct shared));
  30. Ptr=mmap (null,sizeof (struct shared), prot_read| prot_write,map_shared,fd,0);
  31. Sem_init (&ptr->mutex,1,1);
  32. #else
  33. int *ptr;
  34. Sem_t *mutex;
  35. #if Use_shm_open
  36. Fd=shm_open (myshm,o_rdwr| o_creat,0666);
  37. #else
  38. Fd=open (myfile,o_rdwr| o_creat,0666);
  39. #endif
  40. Write (fd,&zero,sizeof (int));
  41. Ptr=mmap (null,sizeof (int), prot_read| prot_write,map_shared,fd,0);
  42. Mutex=sem_open (sem_name,o_creat| o_excl,0666,1);
  43. Sem_unlink (Sem_name);
  44. #endif
  45. Close (FD);
  46. Setbuf (stdout,null);//stdout is unbuffered
  47. if (0==fork ())
  48. {
  49. for (i=0;i<times;i++)
  50. {
  51. #if sem_in_sharememory
  52. Sem_wait (&ptr->mutex);
  53. printf ("Child:%d\n", ptr->count++);
  54. Sem_post (&ptr->mutex);
  55. #else
  56. Sem_wait (mutex);
  57. printf ("Child:%d\n", (*ptr) + +);
  58. Sem_post (mutex);
  59. #endif
  60. }
  61. Exit (0);
  62. }
  63. for (i=0;i<times;i++)
  64. {
  65. #if sem_in_sharememory
  66. Sem_wait (&ptr->mutex);
  67. printf ("Parent:%d\n", ptr->count++);
  68. Sem_post (&ptr->mutex);
  69. #else
  70. Sem_wait (mutex);
  71. printf ("Parent:%d\n", (*ptr) + +);
  72. Sem_post (mutex);
  73. #endif
  74. }
  75. Exit (0);
  76. }
Copy Code

Operation Result:

./a.out
parent:0
Parent:1
Parent:2
Parent:3
Parent:4
Child:5
Child:6
Child:7
Child:8
Child:9


Using a shared memory object mapping by setting "#define Use_shm_open 1", "#define USE_SHM_OPEN 0" uses different file system mappings.
Set "#define Sem_in_sharememory 1" so that the semaphore SEM is also placed in the shared memory area, "#define Sem_in_sharememory 0" so that the semaphore SEM is not in the shared memory area

POSIX shared memory usage and code examples for Linux interprocess communication

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.