资源描述:
《实验三 进程通信》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、-实验三进程通信一.实验学时与类型学时:2,课外学时:自定实验类型:设计性实验二.实验目的了解Linux的软中断、管道、消息队列、共享存储区等进程间通信方式。三.实验内容1.软中断通信机制(1)请编写一个程序:循环输出“howareyou?”,在按下Ctrl+C后中断显示,输出“Byebye!”后退出程序。#include#includeintk=1;voidint_func(intsig)//软中断处理函数{k=0;}Intmain(){signal(SIGINT,int_func);//预置软中断信号处理函数While(k==1)Pr
2、intf(“howareyou?”);Printf(“byebye!”);}(2)使用信号机制实现父子进程同步,父进程先输出A,然后子进程输出B。#include#includeintk=1;voidfunc(intsig){k=0;}main(){intpid;----pid=fork();if(pid>0){printf(“A”);kill(pid,12);}elseif(pid==0){signal(12,func);while(k==1)sleep(1);printf(“B”);}}2.管道机制(1)父子进程通过管道传
3、送一串字符。要求:子进程随机从键盘输入一串字符,通过管道发给父进程,父进程从管道中将消息读出并显示出来。#include#includemain(){intpid,fd[2];charoutpipe[50],inpipe[50];pipe(fd);pid=fork();if(pid==0){Printf(“pleaseinputsomemessage:”);Fgets(inpipe,sizeof(inpipe),stdin);write(fd[1],inpipe,50);}elseif(pid>0);{wait(0);Printf(“
4、fathergetthismessage:”);read(fd[0],outpipe,50);printf(“%s”,outpipe);}}----(2)父子进程通过管道互相发送字符串。要求:子进程向父进程通过管道发送”Iamchild.”,父进程回送”Iamfather.”,父子进程将各自收到的字符串显示在屏幕上。#inlcude#include#includemain(){intpid,fd[2];charstr1[50],str2[50];pipe(fd);pid=fork();if(pid==0){st
5、rcpy(str1,”I’mchild”);write(fd[1],str1,strlen(str1));Sleep(1);read(fd[0],str2,50);printf(“Childreceived:%s”,str2);}elseif(pid>0){read(fd[0],str1,50);printf(“Parentreceived:%s”,str1);strcpy(str2,”I’mfather.”);write(fd[1],str2,strlen(str2));}}3.消息队列机制(1)父进程及其子进程通过一条消息队列互相传送数据。#include6、io.h>#include#include#includeintmsgqid,qid;----structmsg{longmtype;charmtext[256];}pmsg;cancelqueue(){msgctl(msgqid,IPC_RMID,0);exit(0);}main(){intpid;Pid=fork();If(pid>0){msgqid=msgget(75,0777);printf(“msgid:%d”,msgqid);pmsg.mtype=1;*((int*)pmsg.mtext)=
7、getpid();msgsnd(msgqid,&pmsg,sizeof(int),0);msgrcv(msgqid,&pmsg,256,getpid(),0);printf(“A:receivemsgfrom%d",*((int*)pmsg.mtext));}Elseif(pid==0){signal(2,cancelqueue);msgqid=msgget(75,0777
8、IPC_CREAT);while(1){msgrcv(msgqid,&pmsg,256,1,0);qid=*(int*)pms