内存映射实现无血缘关系进程间通信

简介: 内存映射实现无血缘关系进程间通信

创建映射区等知识看上一篇:内存映射实现父子进程通信-CSDN博客

实验结果

这里因为手速原因,id 1~8被覆盖

大致过程:mmap_w.c先向p指针中写如数据 每次让id自增  然后sleep(1)

                 mmap_r.c 在p指针中读数据,打印到屏幕上

代码:

mmap_r.c:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <errno.h>
 
struct student {
   int id;
   int age;
   char name[256];
};
 
void sys_err(const char *str){
    perror(str);
    exit(1);
}
 
int main(int argc,char *argv){
   struct student stu;
   struct student *p;
   int fd;
 
   fd=open("test_map",O_RDONLY);
   if(fd==-1)sys_err("open error");
 
   p=mmap(NULL,sizeof(stu),PROT_READ,MAP_SHARED,fd,0);
   if(p==MAP_FAILED)sys_err("mmap error");
   close(fd);
   while(1){
        printf("id=%d,name=%s,age=%d\n",p->id,p->name,p->age);
        sleep(1);
   }
   munmap(p,sizeof(stu));
   return 0;
}

mmap_w.c:

 

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <errno.h>
 
struct student {
   int id;
   int age;
   char name[256];
};
 
void sys_err(const char *str){
    perror(str);
    exit(1);
}
 
int main(int argc,char *argv){
   struct student stu={1,23,"xiaoming"};
   struct student *p;
   int fd;
 
   fd=open("test_map",O_RDWR|O_CREAT|O_TRUNC,0664);
   if(fd==-1)sys_err("open error");
 
   ftruncate(fd,sizeof(stu));
   p=mmap(NULL,sizeof(stu),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
   if(p==MAP_FAILED)sys_err("mmap error");
   close(fd);
   while(1){
        memcpy(p,&stu,sizeof(stu));
        stu.id++;
        sleep(1);
   }
   munmap(p,sizeof(stu));
   return 0;
}
相关文章
|
1月前
|
消息中间件 算法 Linux
【Linux】详解如何利用共享内存实现进程间通信
【Linux】详解如何利用共享内存实现进程间通信
|
4天前
|
存储 缓存 运维
深入理解操作系统:从进程管理到内存分配
在数字时代的心脏,操作系统扮演着至关重要的角色。本文将深入探讨操作系统的核心机制,包括进程管理、内存分配和文件系统,揭示它们如何协同工作以支持现代计算需求。通过技术深度解析和实际应用示例,我们将一窥操作系统的复杂性与优雅,理解其在软件开发和系统性能优化中的重要性。
|
1月前
|
存储 Web App开发 运维
|
24天前
|
存储 缓存 监控
深度解析操作系统中的核心组件:进程管理与内存优化
【5月更文挑战第29天】 在现代计算技术的心脏,操作系统扮演着至关重要的角色。它不仅管理和控制计算机硬件资源,还为应用程序提供了一个运行环境。本文将深入探讨操作系统中的两个核心组件——进程管理和内存管理,并分析它们对系统性能的影响以及如何通过技术手段实现优化。通过对操作系统内部机制的剖析,我们将揭示这些组件是如何相互作用,以及它们如何共同提升系统的响应速度和稳定性。
|
1月前
|
运维 监控 Ubuntu
Python实现ubuntu系统进程内存监控
Python实现ubuntu系统进程内存监控
27 1
|
1月前
|
消息中间件 存储 安全
【Linux 系统】进程间通信(共享内存、消息队列、信号量)(下)
【Linux 系统】进程间通信(共享内存、消息队列、信号量)(下)
|
1月前
|
消息中间件 算法 Linux
【Linux 系统】进程间通信(共享内存、消息队列、信号量)(上)
【Linux 系统】进程间通信(共享内存、消息队列、信号量)(上)
|
1月前
【进程通信】Syetem V 共享内存(结合代码模拟通信)
【进程通信】Syetem V 共享内存(结合代码模拟通信)
|
1月前
|
消息中间件 Linux
【linux进程间通信(二)】共享内存详解以及进程互斥概念
【linux进程间通信(二)】共享内存详解以及进程互斥概念
|
1月前
内存映射mmap拓展
内存映射mmap拓展

热门文章

最新文章

相关实验场景

更多