linux_使用共享存储映射区进行无血缘进程通信-mmap函数-munmap函数

共享映射区的介绍请看此篇文章:
linux_共享存储映射区-mmap函数-munmap函数-进程通信-strace命令

本篇文章是对共享存储映射区的补充,也是一个例子代码,大家可以借鉴学习。

此博主在CSDN发布的文章目录:【我的CSDN目录,作为博主在CSDN上发布的文章类型导读

1.进程a-先执行-写数据

#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <string.h>
struct student_t {
    int id;
    char name[20];
    char sex;
};
int main(int argc, char *argv[])
{
    int fd;
    struct student_t student = {10, "lisi", 'm'};
    char *mm = NULL;
    fd = open("temp", O_RDWR | O_CREAT, 0664);//打开文件
    if(fd == -1)
    {
        perror("open error");
        exit(1);
    }
    ftruncate(fd, sizeof(student));//拓展文件大小

    mm = mmap(NULL, sizeof(student), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);//创建映射区
    if (mm == MAP_FAILED)
    {
        perror("mmap error");
        exit(1);
    }

    close(fd);
    //循环写数据
    while (1) 
    {
        memcpy(mm, &student, sizeof(student));
        student.id++;
        sleep(1);
    }

    munmap(mm, sizeof(student));

    return 0;
}

2.进程b-后执行-读数据

#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <string.h>

struct student_t {
    int id;
    char name[20];
    char sex;
};

int main(int argc, char *argv[])
{
    int fd;
    struct student_t student;
    struct student_t *mm = NULL;

    fd = open("temp", O_RDONLY);//打开文件
    if (fd == -1)
    {
        perror("open error");
        exit(1);
    }
    mm = mmap(NULL, sizeof(student), PROT_READ, MAP_SHARED, fd, 0);//创建映射区
    if (mm == MAP_FAILED)
    {
        perror("mmap error");
        exit(1);
    }
    close(fd);
    //循环读数据
    while (1) 
    {
        printf("id=%d\tname=%s\t%c\n", mm->id, mm->name, mm->sex);
        sleep(2);
    }
    //释放映射区
    munmap(mm, sizeof(student));
    return 0;
}

以上就是本次的分享了,希望能对大家有所帮助。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

futureCode.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值