使用mmap可以方便地添加共享内存

使用mmap添加的共享内存。

局限:

只能在有亲属关系的进程之间使用。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>
#include <string.h>
#include <wait.h>
//#include <sys/types.h>
//#include <sys/stat.h>
//#include <fcntl.h>

#define MEMSIZE 1024

int main() {
        char *str;
        pid_t pid;

        str = (char *)mmap(NULL, MEMSIZE,
                   PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS,
                   -1, 0);

        if (str == MAP_FAILED) {
                perror("mmap");
                exit(1);
        }

        pid = fork();
        if (pid < 0) {
                perror("fork");
                exit(1);
        }

        if (pid == 0) {
                strncpy(str, "Hello!", 6);
                munmap(str, MEMSIZE);
                printf("child exit\n");
                exit(0);
        }
        else {
                wait(NULL);
                puts(str);
                munmap(str, MEMSIZE);
                printf("father exit\n");
                exit(0);
        }

}

运行结果:

[work@ mmap1]$g++ -o mmap_sharedm mmap_sharedm.cpp
[work@ mmap1]$./mmap_sharedm 
child exit
Hello!
father exit

注意以上各个头文件的作用:

//#include <stdio.h>
mmap_sharedm.cpp:22: error: `perror' was not declared in this scope
mmap_sharedm.cpp:28: error: `perror' was not declared in this scope
mmap_sharedm.cpp:35: error: `printf' was not declared in this scope
mmap_sharedm.cpp:40: error: `puts' was not declared in this scope
mmap_sharedm.cpp:42: error: `printf' was not declared in this scope

//#include <stdlib.h>
mmap_sharedm.cpp:23: error: `exit' was not declared in this scope
mmap_sharedm.cpp:29: error: `exit' was not declared in this scope
mmap_sharedm.cpp:36: error: `exit' was not declared in this scope
mmap_sharedm.cpp:43: error: `exit' was not declared in this scope

//#include <unistd.h>
mmap_sharedm.cpp:26: error: `fork' was not declared in this scope

//#include <sys/mman.h>
mmap_sharedm.cpp:18: error: `PROT_READ' was not declared in this scope
mmap_sharedm.cpp:18: error: `PROT_WRITE' was not declared in this scope
mmap_sharedm.cpp:18: error: `MAP_SHARED' was not declared in this scope
mmap_sharedm.cpp:18: error: `MAP_ANONYMOUS' was not declared in this scope
mmap_sharedm.cpp:19: error: `mmap' was not declared in this scope
mmap_sharedm.cpp:21: error: `MAP_FAILED' was not declared in this scope
mmap_sharedm.cpp:34: error: `munmap' was not declared in this scope
mmap_sharedm.cpp:41: error: `munmap' was not declared in this scope

//#include <string.h>
mmap_sharedm.cpp:33: error: `strncpy' was not declared in this scope

//#include <wait.h>
mmap_sharedm.cpp:39: error: no matching function for call to `wait::wait(NULL)'
/usr/include/bits/waitstatus.h:68: note: candidates are: wait::wait()
/usr/include/bits/waitstatus.h:68: note:                 wait::wait(const wait&)

 

posted @ 2016-04-24 17:05  blcblc  阅读(1768)  评论(0编辑  收藏  举报