资源简介
共享内存的实验,详细看我的博客“Linux进程间通信(十)---综合实验之共享内存实验”
代码片段和文件信息
/* customer.c */
#include“shm_com.h“
#include“sem_com.h“
int main()
{
char *shared_memory=NULL;
struct shm_buff *shm_buff_inst;
int shmidsemid;
/*获得信号量*/
semid=semget(ftok(“.“‘a‘)10666);
if(semid==-1)
{
perror(“Producer isn‘t exist“);
exit(1);
}
/*获得共享内存*/
shmid=shmget(ftok(“.“‘c‘)sizeof(struct shm_buff)0666|IPC_CREAT);
if(shmid==-1)
{
perror(“shmget“);
exit(1);
}
/*将共享内存地址映射到当前进程地址空间*/
shared_memory=shmat(shmid00);
if(shared_memory==(void *)-1)
{
perror(“shmat“);
exit(1);
}
printf(“Memory attached at %p\n“shared_memory);
/*获得共享内存的映射地址*/
shm_buff_inst=(struct shm_buff *)shared_memory;
do
{
sem_p(semid);
printf(“Shared memory was written by process %d : %s“shm_buff_inst->pidshm_buff_inst->buffer);
if(strncmp(shm_buff_inst->buffer“quit“4)==0)
{
perror(“strncmp“);
exit(1);
}
shm_buff_inst->pid=0;
memset(shm_buff_inst->buffer0SHM_BUFF_SZ);
sem_v(semid);
}while(1);
/*删除共享内存到当前进程地址空间中的映射*/
if(shmdt(shared_memory)==-1)
{
perror(“shmdt“);
exit(1);
}
/*删除共享内存*/
if(shmctl(shmidIPC_RMIDNULL)==-1)
{
perror(“shmctl“);
exit(1);
}
exit(0);
}
评论
共有 条评论