MMAP
- mmap is highly similar as shared memory, base on the same kernel implementation.
The simplest code snippet of mmap
#include "apue.h"
#include <sys/mman.h>
#include <string.h>
#include <fcntl.h>
#define PATH "/workspace/c/apue/mmap_x"
#define MESG "Oh Scent"
#define SIZE 1024
char *
mmap_init() {
char *ptr;
int fd;
if ((fd = open(PATH, O_RDWR)) < 0) {
err_sys("open failed");
}
if ((ptr = (char *)mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)) == MAP_FAILED) {
err_sys("mmap failed");
}
return ptr;
}
void
mmap_set(char *ptr) {
}
int
main(void) {
char *ptr;
pid_t pid;
if ((pid = fork()) < 0) {
err_sys("fork failed");
} else if (pid == 0) {
//child
ptr = mmap_init();
printf("child read from mmap file:%s\n", ptr);
exit(0);
}
ptr = mmap_init();
strncpy(ptr, MESG, strlen(MESG));
printf("parent write to mmap file\n");
wait(pid);
exit(0);
}