进程通信之共享内存2

来源:互联网 发布:欧立讯写频软件 编辑:程序博客网 时间:2024/05/18 06:21
#include "6.3 shm_common.h"
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <string.h>


int main()
{
int shmid;
struct share_block *pshare;
char buffer[MAX_SZIE] = {0};
int running = 1;
int ret;


// 创建共享内存或者获取共享内存
shmid = shmget((key_t)1234, sizeof(struct share_block), 0666 | IPC_CREAT);
if (-1 == shmid)
{
perror("shmget");
return -1;
}

// 将共享内存映射到本地空间
pshare = shmat(shmid, NULL, 0);
if ((void *) -1 == pshare)
{
perror("shmat");
return -1;
}


pshare->flag = 0;



while (running)
{
if (0 == pshare->flag)
{
// 从共享内存里读数据
strncpy(buffer, pshare->buffer, MAX_SZIE);
printf("Read data :%s\n", buffer);

// 往共享内存里写入数据
printf("Enter some data to shared memory:");
fgets(buffer, MAX_SZIE, stdin);
if (strncmp("end", buffer, 3) == 0)
{
running = 0;
}
strncpy(pshare->buffer, buffer, MAX_SZIE);
pshare->flag = 1;
}
}


// 解除映射
ret = shmdt(pshare);
if (-1 == ret)
{
perror("shmdt");
return -1;
}


// 删除共享内存
ret = shmctl(shmid, IPC_RMID, NULL);
if (-1 == ret)
{
perror("shmctl");
return -1;
}


return 0;
}