进程间通信之:实验内容

时间:2013-09-13来源:网络

/*将共享内存地址映射到当前进程地址空间*/

shared_memory=shmat(shmid,(void*)0,0);

if(shared_memory==(void*)-1)

{

perror(shmat);

del_sem(semid);

exit(1);

}

printf(Memoryattachedat%Xn,(int)shared_memory);

/*获得共享内存的映射地址*/

shm_buff_inst=(structshared_use_st*)shared_memory;

do

{

sem_p(semid);

printf(Entersometexttothesharedmemory(enter'quit'toexit):);

/*向共享内存写入数据*/

if(fgets(shm_buff_inst->buffer,SHM_BUFF_SZ,stdin)==NULL)

{

perror(fgets);

sem_v(semid);

break;

}

shm_buff_inst->pid=getpid();

sem_v(semid);

}while(strncmp(shm_buff_inst->buffer,quit,4)!=0);

/*删除信号量*/

del_sem(semid);

/*删除共享内存到当前进程地址空间中的映射*/

if(shmdt(shared_memory)==1)

{

perror(shmdt);

exit(1);

}

exit(0);

}

以下是“消费者”程序部分。

/*customer.c*/

#includeshm_com.h

#includesem_com.h

intmain()

{

void*shared_memory=NULL;

structshm_buff*shm_buff_inst;

intshmid,semid;

/*获得信号量*/

semid=semget(ftok(.,'a'),1,0666);

if(semid==-1)

{

perror(Producerisntexist);

exit(1);

}

/*获得共享内存*/

shmid=shmget(ftok(.,'b'),sizeof(structshm_buff),0666|IPC_CREAT);

if(shmid==-1)

{

perror(shmget);

exit(1);

}

/*将共享内存地址映射到当前进程地址空间*/

shared_memory=shmat(shmid,(void*)0,0);

if(shared_memory==(void*)-1)

{

perror(shmat);

exit(1);

}

printf(Memoryattachedat%Xn,(int)shared_memory);

/*获得共享内存的映射地址*/

shm_buff_inst=(structshm_buff*)shared_memory;

do

{

sem_p(semid);

printf(Sharedmemorywaswrittenbyprocess%d:%s

,shm_buff_inst->pid,shm_buff_inst->buffer);

if(strncmp(shm_buff_inst->buffer,quit,4)==0)

{

break;

}

shm_buff_inst->pid=0;

memset(shm_buff_inst->buffer,0,SHM_BUFF_SZ);

sem_v(semid);

}while(1);

/*删除共享内存到当前进程地址空间中的映射*/

if(shmdt(shared_memory)==-1)

{

perror(shmdt);

exit(1);

}

/*删除共享内存*/

if(shmctl(shmid,IPC_RMID,NULL)==-1)

{

perror(shmctl(IPC_RMID));

exit(1);

}

exit(0);

}

4.实验结果

$./producer

MemoryattachedatB7F90000

Entersometexttothesharedmemory(enter'quit'toexit):Firstmessage

Entersometexttothesharedmemory(enter'quit'toexit):Secondmessage

Entersometexttothesharedmemory(enter'quit'toexit):quit

$./customer

MemoryattachedatB7FAF000

Sharedmemorywaswrittenbyprocess3815:Firstmessage

Sharedmemorywaswrittenbyprocess3815:Secondmessage

Sharedmemorywaswrittenbyprocess3815:quit

1 2 3

关键词: 进程间通信 实验 管道通信 Linux 操作系统

加入微信
获取电子行业最新资讯
搜索微信公众号:EEPW

或用微信扫描左侧二维码

相关文章

查看电脑版