[经验分享] 用共享内存读写数据

[复制链接]
16|0
Zhiniaocun 发表于 2026-6-10 17:05 | 显示全部楼层 |阅读模式
31_shm_read.c

#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
//用共享内存读写数据
//读数据到共享内存

/*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
*/






31_shm_write.c

#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:
*/




————————————————
版权声明:本文为CSDN博主「夜星辰2025」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_37787043/article/details/78739142

您需要登录后才可以回帖 登录 | 注册

本版积分规则

172

主题

589

帖子

1

粉丝
快速回复 在线客服 返回列表 返回顶部
0