共享内存很好的例子, 可直接运行.

转子: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:
*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值