您的位置:首页 > 运维架构 > Linux

linux 进程间共享内存

2009-12-16 23:05 113 查看
可以采用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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: