共享内存是IPC的一种机制,允许两个不相关的进程共享同一块内存
//共享内存可以双向通信,但其本身没有相应机制,需要程序编写者设计,本例为单向通信(分为读端和写端)。
共享内存读端:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
//自定义数据结构,flag为同步机制标志:flag 为1表示读端可读, flag为1表示写端可写;str为数据存储的字符数组
struct my_shared
{
int flag;
char str[1024];
};
int main(void)
{
void *shared_memory = NULL;
struct my_shared *shared_buff = NULL;
int running = 1;
int shmid;
//创建共享内存标识
shmid = shmget((key_t)1234, sizeof(struct my_shared), 0666|IPC_CREAT);
if(shmid < 0)
{
perror("fail to shmget");
exit(1);
}
//连接共享内存到进程地址空间
shared_memory = shmat(shmid, NULL, 0);
if(shared_memory == NULL)
{
perror("fail to shmat");
exit(1);
}
shared_buff = (struct my_shared *)shared_memory;
shared_buff->flag = 0;
while(running)
{
//flag为1,读数据
if(shared_buff->flag)
{
printf("shared_memory message is: %s
", shared_buff->str);
shared_buff->flag = 0;
if(strncmp(shared_buff->str, "end", 3) == 0)
{
running = 0;
}
}
}
//把共享从本进程空间分离
if(shmdt(shared_memory) == -1)
{
perror("fail to shmdt");
exit(1);
}
//删除共享内存
if(shmctl(shmid, IPC_RMID, 0) == -1)
{
perror("fail to shmctl");
exit(1);
}
return 0;
}
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
struct my_shared
{
int flag;
char str[1024];
};
int main(void)
{
void *shared_memory = NULL;
struct my_shared *shared_buff = NULL;
int running = 1;
int shmid;
char buffer[512];
shmid = shmget((key_t)1234, sizeof(struct my_shared), 0666|IPC_CREAT);
if(shmid < 0)
{
perror("fail to shmget");
exit(1);
}
shared_memory = shmat(shmid, NULL, 0);
if(shared_memory == NULL)
{
perror("fail to shmat");
exit(1);
}
shared_buff = (struct my_shared *)shared_memory;
shared_buff->flag = 0;
while(running)
{
//flag为1,等等读端读数据
while(shared_buff->flag)
{
printf("wait for other process's reading
");
sleep(2);
}
printf("Please input some data
");
fgets(buffer, 512, stdin);
shared_buff->flag = 1;
strncpy(shared_buff->str, buffer, 1024);
if(strncmp(shared_buff->str, "end", 3) == 0)
{
running = 0;
}
}
if(shmdt(shared_memory) == -1)
{
perror("fail to shmdt");
exit(1);
}
return 0;
}