IPC communication: POSIX shared memory 1

Source: Internet
Author: User

The shared memory zone is the fastest available IPC format. It allows multiple unrelated processes to access the same part of the Logical Memory. To transmit data between two running processes, shared memory is an extremely efficient solution. Once such a memory zone is mapped to the address space of the process that shares it, data transmission between these processes will no longer involve the kernel. This can reduce the system call time and improveProgramEfficiency

Shared Memory is a special address range created by IPC for a process. It will appear in the address space of the process. Other processes can "Connect" the same shared memory segment to their own address space. All processes can access the addresses in the shared memory. If a process writes data to the shared memory, the changes will be immediately seen by other processes that access the same shared memory.

Note that the shared memory itself does not provide any synchronization function. That is to say, there is no automatic function to prevent the second process from reading the shared memory before the write operation of the first process ends. The programmer is responsible for the synchronization of shared memory access. Optional Synchronization Methods include mutex lock, condition variable, read/write lock, record lock, and traffic signal.

Related functions

 1   MMAP () function  2   Function: maps a file or POSIX shared memory area object to the address space of the calling process.  3 Header file: # include <sys/Mman. h> 4 Function prototype:Void * MMAP ( Void * ADDR, size_t Len, Int Prot, Int Flag, Int  Filedes, off_t off );  5   Return Value: If MMAP is successful, the first address of the ing is returned. If an error occurs, the constant map_failed is returned.  6   Parameters:  7   ADDR points to the starting address of the mapped storage area;  8   Len ing bytes 9   Prot protection requirements for mapped storage areas  10   Flag Flag  11   Filedes descriptor of the file to be mapped  12   Off to map the starting offset of the byte in the file  13       14   The parameters are explained as follows: the overall length is equivalent to the size of the disk file to be moved to the memory. If the ADDR parameter is null, the kernel selects an appropriate address in the process address space to create a ing.  15   If ADDR is not null, a prompt is sent to the kernel indicating the address to start ing. The kernel will select a suitable address on the ADDR to start ing. After the ing is established  16  The first address of the ing can be obtained through the return value. The off parameter starts ing from the position of the file and must be page size.  17   Integer multiple (generally 4 K in 32-bit system structure ).  18   The prot parameter has four values:  19   Prot_exec indicates that this segment of ing can be executed, for example, ing a shared library  20   Prot_read indicates the readable part of the ing.  21   Prot_write indicates the writable section of the ing.  22   Prot_none indicates that this segment of the ing is not accessible.  23   There are many flag parameters. Here we only talk about two types, 24   Map_shared multiple processes share the ing of the same file. One process modifies the mapped memory, and the other process also sees this change.  25   Map_private multiple processes do not share the ing of the same file. One process modifies the mapped memory, and the other process does not see this change or  26 Write it to the file.

Note: When a process is terminated, the ing memory of the process is automatically released. You can also call munmap to unbind the ing. If munmap succeeds, 0 is returned, and-1 is returned if an error occurs..

 1   Munmap () function  2   Function: unbind the storage ing.  3 Header file: # include <sys/Mman. h> 4 Function prototype:Int  Munmap (caddr_t ADDR, size_t Len );  5   Parameters:  6   ADDR points to the starting address of the mapped Storage Area  7   Len ing bytes  8 Return Value: if the request succeeds, 0 is returned. If the request fails- 1  9   10   The ADDR parameter is the address returned by MMAP, And Len is the size of the ing area. Accessing these addresses again causes a SIGSEGV signal to be generated to the calling process. If the ing area is used  11 If map_private flag is mapped, all changes made by the calling process are discarded.

Virtual Memory of the kernelAlgorithmKeep the memory ing file (usually on the hard disk) synchronized with the memory ing area (in the memory) (provided that it is in the map_shared memory area ). This means that if we modify the content mapped from memory to a certain location in the memory zone of a file, the kernel will update the file at a certain time later. However, sometimes we want to ensure that the file content on the hard disk is consistent with the file content in the memory ing area, so we call msync to execute this synchronization.

 1   Msync () function  2   Function: Synchronize files to storage.  3 Header file: # include <sys/Mman. h> 4 Function prototype: Int Msync ( Void * ADDR, size_t Len, Int  Flags );  5  Parameters:  6   ADDR points to the starting address of the mapped Storage Area  7   Len ing bytes  8   The flags parameter is ms_async (asynchronous write execution), ms_sync (synchronous write execution), and ms_invalidate (to make the cache data effective ).  9   Either ms_async or ms_sync must be specified. The difference between them is that once a write operation has been queued by the kernel,  10   Ms_async is returned, while ms_sync is returned after the write operation is complete. If ms_invalidate is specified  11   All copies in the memory are invalid. Subsequent references will retrieve data from the file. 12 Return Value: if the request succeeds, 0 is returned. If the request fails- 1  13   14   15   Memcpy () function  16   Function: copies and maps data to a storage area.  17 Header file: # include < String . H> 18 Original function: Void * Memcpy ( Void * DEST, Const   Void * SRC, size_t N );  19   Parameters:  20   DeST ing storage area to be copied  21   Mapped storage area after SRC Replication  22   N size of the mapped storage area to be copied  23 Return Value: return the first DEST address.

ExampleCode:

 /*  Mycp. c  */  # Include <Unistd. h> # Include <Stdlib. h> # Include < String . H> # Include <Stdio. h> # Include <Fcntl. h> # Include <Sys/Mman. h> # Include <Sys/STAT. h> # Include <Sys/types. h> Int Main ( Int Argc, Char *Argv []) {  Int  Fdin, fdout;  Void * SRC ,* DST;  Struct  Stat statbuf;  If (Argc! = 3  ) {Printf (  "  Please input two file! \ N  "  ); Exit (  1 );}  /*  Open the original file  */      If (Fdin = open (argv [ 1 ], O_rdonly) < 0  ) Perror (argv [  1  ]);  /*  Create and open the target file  */      If (Fdout = open (argv [ 2 ], O_rdwr | o_creat | o_trunc) <0  ) Perror (argv [  2  ]);  /*  Obtain file size information  */      If (Fstat (fdin, & statbuf) < 0  ) Printf (  "  Fstat Error  "  );  /*  Initialize the output ing storage area */      If (Lseek (fdout, statbuf. st_size- 1 , Seek_set) =- 1  ) Printf (  "  Lseek Error  "  );  If (Write (fdout, "  1  " , 1 )! = 1 ) Printf (  "  Write Error  "  );  /*  Map the original file to the input ing storage area  */      If (Src = MMAP ( 0 , Statbuf. st_size, prot_read, map_shared, fdin, 0 ) = Map_failed) printf (  "  MMAP Error  " );  /*  Map the target file to the output mapped Storage Area  */       If (DST = MMAP ( 0 , Statbuf. st_size, prot_read | prot_write, map_shared, fdout, 0 ) = Map_failed) printf (  "  MMAP Error  "  ); Memcpy (DST, SRC, statbuf. st_size );  /*  Copy ing storage area */  Munmap (SRC, statbuf. st_size );  /*  Uninput ing  */  Munmap (DST, statbuf. st_size );  /*  Release output ing  */  Close (fdin); close (fdout );} 

Compile and run:

1Root @ Linux:/mnt/HGFS/C_libary # vi mycp. c2Root @ Linux:/mnt/HGFS/c_libary # gcc-O mycp. c3Root @ Linux:/mnt/HGFS/c_libary #./Mycp test1.txt test2.txt4Root @ Linux:/mnt/HGFS/C_libary # More test2.txt5Hello world!

 

 

 

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.