linux共享内存的理解
http://www.ibm.com/developerworks/cn/linux/l-ipc/part5/index1.html
http://www.cnblogs.com/huxiao-tee/p/4660352.html
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#define ARGC_NUMS 3
int main(int argc, char *argv[]) {
int src_fd;
int dst_fd;
struct stat sb;
void *src_addr = NULL;
void *dst_addr = NULL;
if (argc != ARGC_NUMS) {
fprintf(stderr, "Usage: %s \n ", argv[0]);
exit(EXIT_FAILURE);
}
src_fd = open(argv[1], O_RDONLY);
if (src_fd < 0) {
fprintf(stderr, "Error: open file %s failed, error(%d):%s\n", argv[1],
errno, strerror(errno));
exit(EXIT_FAILURE);
}
if (fstat(src_fd, &sb) == -1) {
fprintf(stderr, "Error: fstat file %s(fd: %d) failed, error(%d):%s",
argv[1], src_fd, errno, strerror(errno));
exit(EXIT_FAILURE);
}
dst_fd = open(argv[2], O_RDWR | O_CREAT | O_TRUNC, 0600);
if (dst_fd < 0) {
fprintf(stderr, "Error: open file %s failed, error(%d):%s\n", argv[2],
errno, strerror(errno));
exit(EXIT_FAILURE);
}
if (lseek(dst_fd, sb.st_size, SEEK_SET) < 0) {
fprintf(stderr, "Error: lseek failed, error(%d):%s\n", errno, strerror(
errno));
exit(EXIT_FAILURE);
}
write(dst_fd, "A", 1);
src_addr = mmap(0, (size_t) sb.st_size, PROT_READ, MAP_PRIVATE
| MAP_NORESERVE, src_fd, 0);
if (MAP_FAILED == src_addr) {
fprintf(stderr, "Error: map source failed, error(%d):%s\n", errno,
strerror(errno));
exit(EXIT_FAILURE);
}
dst_addr = mmap(0, (size_t) sb.st_size, PROT_WRITE, MAP_SHARED,
dst_fd, 0);
if (MAP_FAILED == dst_addr) {
fprintf(stderr, "Error: map dest failed, error(%d):%s\n", errno,
strerror(errno));
exit(EXIT_FAILURE);
}
memcpy(dst_addr, src_addr, (size_t) sb.st_size);
munmap(src_addr, (size_t) sb.st_size);
munmap(dst_addr, (size_t) sb.st_size);
close(src_fd);
close(dst_fd);
exit(EXIT_SUCCESS);
}