Webserver(2.7)共享内存
目录
- 共享内存
- 共享内存实现进程通信
共享内存
共享内存比内存映射效率更高,因为内存映射关联了一个文件
共享内存实现进程通信
write.c
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>int main(){//1.创建一个共享内存int shmid=shmget(100,4096,IPC_CREAT|0664);//2.和当前进程进行关联void *ptr=shmat(shmid,NULL,0);char * str ="hello world";//3.写数据memcpy(ptr,str,strlen(str)+1);printf("按任意键继续\n");getchar();//4.解除关联shmdt(ptr);//5.删除共享内存shmctl(shmid,IPC_RMID,NULL);return 0;
}
read.c
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>int main(){//1.获取一个共享内存int shmid=shmget(100,0,IPC_CREAT);//2.和当前进程进行关联void *ptr=shmat(shmid,NULL,0);char * str ="hello world";//3.读数据printf("%s\n",(char *)ptr);printf("按任意键继续\n");getchar();//4.解除关联shmdt(ptr);//5.删除共享内存shmctl(shmid,IPC_RMID,NULL);return 0;
}