Linux system programming: inter-process communication-mmap, linux-mmap
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(void *addr, size_t length);
In essence, mmap synchronizes the memory with files on the hard disk. The content in a memory is synchronized to the hard disk file, that is, the file is mapped to the memory. Therefore, communication between processes is achieved through reading and writing the same file.
Parameter description:
Addr: Specifies the memory block to be mapped. NULL indicates that it is allocated by the system.
Length: length of addr
Prot: Attributes of memory blocks: read, write, and execute.
Flag: whether the content of the memory block is synchronized to the file. MAP_SHARED synchronization, MAP_PRIVATE is not synchronized.
Fd: file descriptor
Offset: Start position of file ing
Success: returns the mapped memory address; 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 = mmap(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);printf("%s\n", mem);*(char*)mem = 'Z';*(char*)(mem + 1) = 'X';if(-1 == munmap(mem, len))sys_err("munmap");return 0;}
File: zhangxiang
$ gcc mmap.c$ ./a.out file$ cat fileZXangxiang
With the above foundation, it is easy to use mmap for inter-process communication.
CCPP Blog directory
Copyright Disclaimer: This article is an original article by the blogger. For more information, see the source.