- void *mmap (void *addr,size_t len,int prot,int flags, int fd,off_t offset);
- Prot: Protection method
- Prot_read: Page readable
- Prot_write: Page writable
- Prot_exec:
- Prot_none:
- Fiags:
- Map_shared:
- Map_private: The change is private
- Map_fixed: Accurate explanation of addr
- Map_anonymous: Set up anonymous mappings, no files involved
- Mmap is to reverse the memory in a page, memory is an integer multiple of the page
- int munmmap (int fd,size_t size)
- int Msync (void *addr, size_t len,int flags)
- Flags
- Ms_anync: Performing asynchronous writes
- Ms_sync: Performing Synchronous writes
- MS_INVALIDATR: Cache is invalid
- Attention
- The map cannot change the size of the file
- Give me a chestnut.
1 //Create shared Memory2#include <sys/mman.h>3#include <unistd.h>4#include <sys/types.h>5 6#include <stdlib.h>7#include <stdio.h>8#include <errno.h>9#include <sys/stat.h>Ten#include <fcntl.h> One A #defineErr_exit (M) - Do - { the perror (m); - exit (exit_failure); -} while(0) - +typedefstructSTT - { + Charname[4]; A intAge ; at }stu; - - intMainintargcChar*argv[]) - { - if(ARGC! =2) - { in exit (exit_failure); - } to + intFD; -FD = open (argv[1], O_creat | O_rdwr | O_trunc,0666); the if(FD = =-1) * { $Err_exit ("Open");Panax Notoginseng } -Lseek (FD,sizeof(STU) *5-1, seek_set); theWrite (FD,"",1); +STU *p; Ap = (stu*) mmap (NULL,sizeof(STU) *5, Prot_read | PROT_WRITE,MAP_SHARED,FD,0); the if(p = =NULL) +Err_exit ("mmap"); - CharCH ='a'; $ inti; $ for(i =0;i<5; i++) - { -memcpy (p+i)->name,&ch,1); the(p+i)->age= -+i; -ch++;Wuyi } theprintf"initlize over!\n"); -Munmap (P,sizeof(STU) *5); Wuprintf"exit....\n"); - return 0; About}
1 //Read Shared memory2#include <sys/mman.h>3#include <unistd.h>4#include <sys/types.h>5 6#include <stdlib.h>7#include <stdio.h>8#include <errno.h>9#include <sys/stat.h>Ten#include <fcntl.h> One A #defineErr_exit (M) - Do - { the perror (m); - exit (exit_failure); -} while(0) - +typedefstructSTT - { + Charname[4]; A intAge ; at }stu; - - intMainintargcChar*argv[]) - { - if(ARGC! =2) - { in exit (exit_failure); - } to + intFD; -FD = open (argv[1], O_RDWR); the if(FD = =-1) * { $Err_exit ("Open");Panax Notoginseng } - theSTU *p; +p = (stu*) mmap (NULL,sizeof(STU) *5, Prot_read | PROT_WRITE,MAP_SHARED,FD,0); A if(p = =NULL) theErr_exit ("mmap"); + CharCH ='a'; - inti; $ for(i =0;i<5; i++) $ { -printf"name =%s, age =%d\n", (P+i)->name, (P+i),Age ); - } theMunmap (P,sizeof(STU) *5); -printf"exit....\n"); Wuyi return 0; the}
System v Shared Memory
- Persist with the kernel (same message queue)
1 //Shared Memory Functions2#include <sys/ipc.h>3#include <sys/shm.h>4 5 //Create or access a shared memory6 intShmget (key_t key,size_t size,intSHMFLG);7 //Mapping8 void* Shmat (intShmid,Const void*SHMADDR,intSHMFLG);9 //detachedTen intSHMDT (Const void*shmaddr); One //Control A intShmctl (intShimid,intCmdstructShmid_ds *buf);
interprocess communication-Shared memory