可以采用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;
}