新闻中心

EEPW首页 > 嵌入式系统 > 设计应用 > 进程间通信之:实验内容

进程间通信之:实验内容

作者: 时间:2013-09-13 来源:网络 收藏

本文引用地址:https://www.eepw.com.cn/article/257122.htm

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

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

linux操作系统文章专题:linux操作系统详解(linux不再难懂)

数字通信相关文章:数字通信原理


通信相关文章:通信原理



上一页 1 2 3 下一页

评论


相关推荐

技术专区

关闭