linux共享内存简析

共享内存是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\n", 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\n");
sleep(2);
}

printf("Please input some data\n");
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;

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值