转子:https://blog.csdn.net/weixin_37787043/article/details/78739142
#include<stdio.h>
#include<stdlib.h>
#include<sys/ipc.h>
#include <sys/types.h>
#include<sys/shm.h>
#include<string.h>
#include <unistd.h>
#define SHM_SIZE 1024
//用共享内存读写数据
//读数据到共享内存
/*int shmctl(int shmid, int cmd, struct shmid_ds *buf);删除共享内存
参数2: IPC_STAT (获取对象属性)
IPC_SET (设置对象属性)
IPC_RMID (删除对象)
参数3:一般删除对象填NULL
*/
int main()
{
//1.创建共享内存
key_t key = ftok(".",'a');
int shmid = -1;
shmid = shmget(key,SHM_SIZE,IPC_CREAT | 0666);
if(shmid < 0)
{
perror("shmget");
exit(1);
}
//2.映射
char *ptr = NULL;
ptr = shmat(shmid,NULL,0);//0表示共享内存可读可写
if(ptr == (void *)-1)
{
perror("shmat");
exit(1);
}
//3.读数据
while(1)
{
if(ptr[0] != '\0')//厉害
printf("ptr = %s\n",ptr);
if(!strncmp(ptr,"quit",4))
break;
//必须要手动清空
memset(ptr,0,SHM_SIZE);//清空内存
sleep(1);//因为没有阻塞
}
//4.解除共享内存映射
if(shmdt(ptr) < 0)
{
perror("shmdt");
exit(1);
}
//5.删除共享内存
if(shmctl(shmid,IPC_RMID,NULL) == -1)
{
perror("shmctl");
exit(1);
}
}
/*
$ ./31_shm_read
ptr = hello
ptr = woooooo
*/
#include<stdio.h>
#include<stdlib.h>
#include<sys/ipc.h>
#include <sys/types.h>
#include<sys/shm.h>
#include<string.h>
#define SHM_SIZE 1024
//用共享内存读写数据
//写数据到共享内存
//媒介是ptr
int main()
{
//1.创建共享内存
key_t key = ftok(".",'a');//键一定要唯一
int shmid = -1;
shmid = shmget(key,SHM_SIZE,IPC_CREAT | 0666);//返回值为id号
if(shmid < 0)
{
perror("shmget");
exit(1);
}
//2.映射
char *ptr = NULL;
ptr = shmat(shmid,NULL,0);// 返回值为被映射的段地址
if(ptr == (void *)-1)
{
perror("shmat");
exit(1);
}
//3.写数据
char buf[128];
while(1)
{
fprintf(stderr,"input:");
fgets(buf,127,stdin);
strncpy(ptr,buf,strlen(buf));
if(!strncmp(buf,"quit",4))
break;
}
//4.解除共享内存映射
if(shmdt(ptr) < 0)
{
perror("shmdt");
exit(1);
}
//5.写端一般不要删除
}
/*
$ ./31_shm_write
input:hello
input:woooooo
input:
*/