linux 进程间共享内存

可以采用sysV的shmget + shmat 实现。

但是我更喜欢shm_open + mmap 更简单。

#---------------------writer.c----------------------------

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

struct ofs_stat
{
  int a;
  int b;
  int c;
};

int main(void)
{
        int fd;
    int count = 0;
    struct ofs_stat stat={0};
    struct ofs_stat *s;
    void *region=NULL;
    char *name;

        if((fd=shm_open("ofs_mmm", O_TRUNC|O_CREAT|O_RDWR,0644))==-1) {
      perror("open");
      exit(1);
        }

    ftruncate(fd, sizeof(stat));
    region = mmap(NULL, sizeof(struct stat), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
    if(region == (caddr_t)-1) {
      perror("mmap");
      shm_unlink("ofs_mmm");
      return 1;
    }
    s = (struct ofs_stat *)region;
    while(1) {
      s->a=count++;
      printf("%d /n",s->a);
      sleep(1);
    }
        shm_unlink("ofs_mmm");
    return 0;
}
#--------------------reader.c----------------------------

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

struct ofs_stat
{
  int a;
  int b;
  int c;
};

int main(void)
{
        int fd;
    int count = 0;
    struct ofs_stat stat={0};
    struct ofs_stat *s;
    void *region=NULL;
    char *name;

        if((fd=shm_open("ofs_mmm", O_CREAT|O_RDONLY,0644))==-1) {
      perror("open");
      exit(1);
        }
    ftruncate(fd, sizeof(struct stat));
    region = mmap(NULL, sizeof(struct stat), PROT_READ, MAP_SHARED, fd, 0);
    if(region == (caddr_t)-1) {
      perror("mmap");
      shm_unlink("ofs_mmm");
      return 1;
    }
    s = (struct ofs_stat *)region;
    while(1) {
      printf("%d /n",s->a);
      sleep(1);
    }
        shm_unlink("ofs_mmm");
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值