特别注意在使用命名文件mem.txt做映射前,切记要在mem.txt中先写入字符串。
多个线程共用一个mmap映射空间。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
int main(int * argc, char * argv[])
{
char buf[1024] = {0};
int fd = open(“mem.txt”,O_RDWR);
if(fd == -1) perror(“fd fail\n”);
char * mem = mmap(NULL, 80, PROT_READ|PROT_WRITE, MAP_SHARED ,fd,0);
if(mem == MAP_FAILED) perror(“MAP fail\n”);
//strcpy(mem,“main”);
//char * str = strcpy(mem,“hello”);
//if(*str == -1) perror(“strcpy error”);
//*mem = 100;
int i;
pid_t pid;
for(i = 0; i < 2; i++)
{
pid = fork();
//exit(1);
if(pid == 0) break;//pid == 0,是子线程逻辑,创建完后退出,该子线程退出这个for循环,pcb中保存当前i的值。
}
if(pid == -1) perror("fork fail\n");
if(pid > 0) //父进程逻辑
{
sleep(1);
strcpy(buf,mem);
printf("buffer : %s\n", buf);
sleep(2);
strcpy(buf,mem);
printf("buffer : %s\n", buf);
}
else if(pid == 0)//子进程逻辑
{
printf("i = %d\n",i);
// strcpy(mem,"child0 write data");
if(i == 0)
{
strcpy(mem,"child0 write data");
}
if(i == 1)
{
sleep(2);
strcpy(mem,"child1 write data");
}
}
sleep(1);
munmap(mem, 80);
close(fd);
return 0;
}