共享内存是不同进程间通过访问同一段逻辑内存,实现数据共享,非常方便。下面是一个简单实例
在share_write.c中
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/shm.h>
int main(int argc, char *argv[])
{
int shmid = 0;
int share_len = 64;
void *shm = NULL;
shmid = shmget((key_t)1000, share_len, 0666 | IPC_CREAT);
if (shmid == -1)
{
printf("shmget fail\n");
}
shm = shmat(shmid, 0, 0);
if (shm == (void *) - 1)
{
printf("shmat fail\n");
}
strcpy(shm, "TEST");
printf("Contents of share memory: %s\n", shm);
if (shmdt(shm) == -1)
{
printf("shmdt fail\n");
}
return 0;
}
在share_read.c中
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/shm.h>
int ma