【博客171】IPC(进程间通信)——共享内存(二)

内容:记录进程间的另一种通信方式:共享内存(mmap)

函数接口:

#include <sys/mman.h>
void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);
int munmap(void *addr, size_t length);

代码实践:

//发送
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <stdlib.h>
 
 
int main(void)
{
    int fd = open("test.txt",O_RDWR|O_CREAT,0664);
    if(fd==-1)
    {
        perror("open flie error\n");
        exit(1);
    }
    ftruncate(fd,4096);
    int len = lseek(fd,0,SEEK_END);
    void* ptr = mmap(NULL,len,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
    if(ptr == MAP_FAILED)
    {
        perror("mmap error\n");
        exit(1);
    }
    char* temp = (char*)ptr;
    int count = 1;
    while(1)
    {
        char str[1024]={0};
        sprintf(str,"hello world ! the num:%d\n",count);
        strcpy(temp,str);
        printf("write :%s\n",temp);
        temp += strlen(str);
        sleep(1);
        count++;
    }
    int ret = munmap(ptr,len);
    if(ret==-1)
    {
        perror("munmap error \n");
        exit(1);
    }
    close(fd);
    return 0;
}

//读取
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
 
 
int main(void)
{
    int fd = open("test.txt",O_RDWR|O_CREAT,0664);
    if(fd==-1)
    {
        perror("open file error \n");
        exit(1);
    }
    ftruncate(fd,4096);
    int len = lseek(fd,0,SEEK_END);
    void* ptr = mmap(NULL,len,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
    if(ptr == MAP_FAILED)
    {
        perror("mmap error\n");
        exit(1);
    }
    char* temp = (char*)ptr;
    while(1)
    {
        char str[1024] = {0};
        strcpy(str,temp);
        printf("%s\n",str);
        temp += strlen(str);
        sleep(2);
    }
    int ret = munmap(ptr,len);
    if(ret==-1)
    {
        perror("munmap error \n");
        exit(1);
    }
    close(fd);
    return 0;
}

运行结果:
发送端:
在这里插入图片描述
接收端:
在这里插入图片描述
mmap的详细介绍看另一篇:
【博客170】IPC(进程间通信)——共享内存(一)

大四学生一枚,如果文章有错误的地方,欢迎在下方提出,每条评论我都会去认真看并回复,同时感谢指正的前辈。有喜欢C/C++,linux的同学欢迎私信一起讨论学习。

发布了214 篇原创文章 · 获赞 41 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_43684922/article/details/104464735