Inter-process Communication-mmap
#include <sys/mman.h>void *mmap (void *addr, size_t length, int prot, int flags, int fd, off_t offset); int Munmap (voi D *addr, size_t length);
The essence of mmap is to synchronize the memory with the files on the hard disk. The contents of a block of memory are synced to the hard disk file, which maps the files to memory. Therefore, the communication between processes is achieved through the reading and writing of the same file.
Parameter explanation:
Addr: Specifies where to map the block of memory. A null representation is assigned by the system.
Length of Length:addr
Prot: Properties of Memory Blocks: Read, write, execute.
Flag: The contents of the memory block are synchronized to the file. Map_shared synchronization, map_private out of sync.
FD: File descriptor
Offset: The starting position of the file map
Succeeds, returns the mapped memory address; the failure returns void * (-1).
Mmap.c
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include < sys/stat.h> #include <fcntl.h> #include <sys/mman.h>void sys_err (char *s) {perror (s); exit (1);} int main (int argc, char **argv) {if (ARGC < 2) {fprintf (stdin, "usage:./a.out filename"); return 1;} int fd;fd = open (argv[1], O_RDWR), if (FD < 0) Sys_err ("Open"), off_t Len;len = Lseek (FD, 0, seek_end); void *mem;mem = MMA P (NULL, Len, Prot_write, map_shared, FD, 0), if (mem = = map_failed) //#define MAP_FAILED ((void *)-1) sys_err ("Mmap"); *if ((void*)-1 = = mem) sys_err ("Mmap"), */close (FD);p rintf ("%s\n", mem), * (char*) mem = ' Z '; * (char*) (mem + 1) = ' X '; if ( -1 = = m Unmap (Mem, Len)) Sys_err ("Munmap"); return 0;}
File File:zhangxiang
$ gcc mmap.c$./a.out file$ Cat Filezxangxiang
with the above foundation, it is easy to communicate between processes using MMAP.
CCPP Blog Directory
Copyright NOTICE: This article is for bloggers original articles, reproduced, please indicate the source.
Linux system programming: interprocess communication-mmap