1.不同进程间通信
1.1 写进程:
#include <sys/mman.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <cstring>
struct Person {
int age;
char name[256];
};
int main() {
printf("write process");
Person pa = {1, "heyan"};
Person *pb;
int fd = open("mmap.txt", O_RDWR | O_CREAT | O_TRUNC, 0644);
if (fd == -1) {
printf("open mmap.txt filed");
exit(1);
}
printf("open mmap.txt success\n");
//扩充文件大小,否则mmap读时会发生总线错误
ftruncate(fd, sizeof(Person));
pb = (static_cast<Person *>(mmap(NULL, sizeof(Person), PROT_WRITE, MAP_SHARED, fd, 0)));
if (pb == MAP_FAILED) {
printf("mmap open failed\n");
exit(1);
}
close(fd);
printf("mmap open success\n");
int i = 0;
while (i<11) {
printf("write\n");
memcpy(pb, &pa, sizeof(Person));
pa.age++;
sleep(1);
i++;
}
munmap(pb, sizeof(Person));
return 0;
}
1.2 读进程:
#include <sys/mman.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <cstring>
#include <iostream>
struct Person {
int age;
char name[256];
};
int main() {
printf("read process");
Person pa;
Person *pb;
int fd = open("mmap.txt", O_RDONLY, 0644);
if (fd == -1) {
printf("open mmap.txt filed");
exit(1);
}
printf("open mmap.txt success\n");
//扩充文件大小,否则mmap读时会发生总线错误
pb = (static_cast<Person *>(mmap(NULL, sizeof(pa), PROT_READ, MAP_SHARED, fd, 0)));
if (pb == MAP_FAILED) {
printf("mmap open failed\n");
exit(1);
}
close(fd);
printf("mmap open success");
int i = 0;
while (i < 11) {
printf("age = %d name = %s\n", pb->age, pb->name);
sleep(1);
i++;
}
munmap(pb, sizeof(pa));
return 0;
}
写进程先运行,运行结果:
write processopen mmap.txt success
mmap open success
write
write
write
write
write
write
write
write
write
write
write
读进程结果:
age = 5 name = heyan
age = 6 name = heyan
age = 7 name = heyan
age = 8 name = heyan
age = 9 name = heyan
age = 10 name = heyan
age = 11 name = heyan
age = 11 name = heyan
age = 11 name = heyan
age = 11 name = heyan
写进程先开始,会覆盖之前的数据,在读时就不是从1开始了。所以读到的结果是从5开始,因为读进程又是后结束,所以杜金城会读到11几次,因为11是写进程最后写入的数据。