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

时间:2023-03-09 09:15:32
使用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,
-, ); if (str == MAP_FAILED) {
perror("mmap");
exit();
} pid = fork();
if (pid < ) {
perror("fork");
exit();
} if (pid == ) {
strncpy(str, "Hello!", );
munmap(str, MEMSIZE);
printf("child exit\n");
exit();
}
else {
wait(NULL);
puts(str);
munmap(str, MEMSIZE);
printf("father exit\n");
exit();
} }

运行结果:

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

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

//#include <stdio.h>
mmap_sharedm.cpp:: error: `perror' was not declared in this scope
mmap_sharedm.cpp:: error: `perror' was not declared in this scope
mmap_sharedm.cpp:: error: `printf' was not declared in this scope
mmap_sharedm.cpp:: error: `puts' was not declared in this scope
mmap_sharedm.cpp:: error: `printf' was not declared in this scope //#include <stdlib.h>
mmap_sharedm.cpp:: error: `exit' was not declared in this scope
mmap_sharedm.cpp:: error: `exit' was not declared in this scope
mmap_sharedm.cpp:: error: `exit' was not declared in this scope
mmap_sharedm.cpp:: error: `exit' was not declared in this scope //#include <unistd.h>
mmap_sharedm.cpp:: error: `fork' was not declared in this scope //#include <sys/mman.h>
mmap_sharedm.cpp:: error: `PROT_READ' was not declared in this scope
mmap_sharedm.cpp:: error: `PROT_WRITE' was not declared in this scope
mmap_sharedm.cpp:: error: `MAP_SHARED' was not declared in this scope
mmap_sharedm.cpp:: error: `MAP_ANONYMOUS' was not declared in this scope
mmap_sharedm.cpp:: error: `mmap' was not declared in this scope
mmap_sharedm.cpp:: error: `MAP_FAILED' was not declared in this scope
mmap_sharedm.cpp:: error: `munmap' was not declared in this scope
mmap_sharedm.cpp:: error: `munmap' was not declared in this scope //#include <string.h>
mmap_sharedm.cpp:: error: `strncpy' was not declared in this scope //#include <wait.h>
mmap_sharedm.cpp:: error: no matching function for call to `wait::wait(NULL)'
/usr/include/bits/waitstatus.h:: note: candidates are: wait::wait()
/usr/include/bits/waitstatus.h:: note: wait::wait(const wait&)