写的部分
#include<stdio.h>
#include<sys/shm.h>
#include<stdlib.h>
#include<string.h>
#include<sys/ipc.h>
int main()
{
int shmid;
char *shmaddr;
key_t key;
key = ftok(".",1);//获取key的ID值
shmid = shmget(key,1024*4,IPC_CREAT|0666);//创建共享内存
if(shmid == -1){//测试是否创建成功,-1为创建失败
printf("shmget no OK\n");
exit(-1);
}
shmaddr = shmat(shmid,0,0);//映射
printf("shmat ok\n");
strcpy(shmaddr,"liuzhihao");//传递数据
sleep(5);//睡5秒
shmdt(shmaddr);//释放共享内存数据
shmctl(shmid,IPC_RMID,0);删除共享内存
printf("quit\n");//打印退出
return 0;
}
~
~
读的部分
#include<stdio.h>
#include<sys/shm.h>
#include<stdlib.h>
#include<string.h>
#include<sys/ipc.h>
int main()
{
int shmid;
char *shmaddr;
key_t key;
key = ftok(".",1);//获取key的ID值
shmid = shmget(key,1024*4,0);//创建共享内存
if(shmid == -1){
printf("shmget no OK\n");
exit(-1);
}
shmaddr = shmat(shmid,0,0);//映射
printf("shmat ok\n");
printf("data:%s \n",shmaddr);//打印输出数据
shmdt(shmaddr);//释放读取的数据
printf("quit\n");//打印关闭
return 0;
}
~
写的界面显示
CLC@Embed_Learn:~/liuzhihao$ ./w
shmat ok
quit
读的界面显示
CLC@Embed_Learn:~/liuzhihao$ ./r
shmat ok
data:liuzhihao
quit
查看删除共享内存
CLC@Embed_Learn:~/liuzhihao$ ipcs -m
------ Shared Memory Segments --------
key shmid owner perms bytes nattch status
0x00000000 0 CLC 600 393216 2 dest
0x00000000 32769 CLC 600 393216 2 dest
0x01056453 524290 CLC 666 4096 0
CLC@Embed_Learn:~/liuzhihao$ ipcrm -m 524290
CLC@Embed_Learn:~/liuzhihao$ ipcs -m
------ Shared Memory Segments --------
key shmid owner perms bytes nattch status
0x00000000 0 CLC 600 393216 2 dest
0x00000000 32769 CLC 600 393216 2 dest