一、创建或者打开共享内存
shmget(key_t key,
size_t size,//共享内存段的大小
int flag);//打开:0,创建:IPC_CREAT|0644
查看共享内存:
ipcs -m
具体案例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/shm.h>
#include <sys/ipc.h>
struct stu{
int id;
char name[20];
};
int main(void)
{
int shmid=shmget(1234,sizeof(struct stu),IPC_CREAT|0644);
if(shmid==-1) perror("shmget"),exit(1);
printf("create ok\n");
}
二、让共享内存和本进程建立联系
shmat(int id,
const char *shmaddr,//想让操作系统挂到这个地址空间
NULL //让操作系统自己选择
int flag);//0
返回值:实际挂载到的虚拟地址的起始地址
三、卸载掉共享内存
int shmdt(void *shmadr);//
具体案例:
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/shm.h>
#include <sys/ipc.h>
struct stu{
int id;
char name[20];
};
int main(void)
{
int shmid=shmget(1234,sizeof(struct stu),0);
if(shmid==-1) perror("shmget"),exit(1);
struct stu *p=(struct stu*)shmat(shmid,NULL,0);
assert(p!=NULL);
p->id=1;
strcpy(p->name,"小猪佩奇");
sleep(20);
shmdt(p);
}
四、删除共享内存
int shmctl(int id,
int cmd,//IPC_RMID 删除共享内存
NULL);
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int main(void)
{
int id=shmget(1234,0,0);
shmctl(id,IPC_RMID,NULL);
}