实验三-进程通信

实验三-进程通信

ID:23210304

大小:174.50 KB

页数:12页

时间:2018-11-04

实验三-进程通信_第1页
实验三-进程通信_第2页
实验三-进程通信_第3页
实验三-进程通信_第4页
实验三-进程通信_第5页
资源描述:

《实验三-进程通信》由会员上传分享,免费在线阅读,更多相关内容在应用文档-天天文库

1、实验三进程通信一.实验学时与类型学时:2,课外学时:自定实验类型:设计性实验二.实验目的了解Linux的软中断、管道、消息队列、共享存储区等进程间通信方式。三.实验内容1.软中断通信机制(1)请编写一个程序:循环输出“howareyou?”,在按下Ctrl+C后中断显示,输出“Byebye!”后退出程序。#include#includeintk=1;voidint_func(intsig)//软中断处理函数{k=0;}Intmain(){signal(SIGINT,int_func

2、);//预置软中断信号处理函数While(k==1)Printf(“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);w

3、hile(k==1)sleep(1);printf(“B”);}}2.管道机制(1)父子进程通过管道传送一串字符。要求:子进程随机从键盘输入一串字符,通过管道发给父进程,父进程从管道中将消息读出并显示出来。#include#includemain(){intpid,fd[2];charoutpipe[50],inpipe[50];pipe(fd);pid=fork();if(pid==0){Printf(“pleaseinputsomemessage:”);Fgets(in

4、pipe,sizeof(inpipe),stdin);write(fd[1],inpipe,50);}elseif(pid>0);{wait(0);Printf(“fathergetthismessage:”);read(fd[0],outpipe,50);printf(“%s”,outpipe);}}(2)父子进程通过管道互相发送字符串。要求:子进程向父进程通过管道发送”Iamchild.”,父进程回送”Iamfather.”,父子进程将各自收到的字符串显示在屏幕上。#inlcude#inc

5、lude#includemain(){intpid,fd[2];charstr1[50],str2[50];pipe(fd);pid=fork();if(pid==0){strcpy(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);prin

6、tf(“Parentreceived:%s”,str1);strcpy(str2,”I’mfather.”);write(fd[1],str2,strlen(str2));}}3.消息队列机制(1)父进程及其子进程通过一条消息队列互相传送数据。#include#include#include#includeintmsgqid,qid;structmsg{longmtype;charmtext[256];}pmsg;cancelq

7、ueue(){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)=getpid();msgsnd(msgqid,&pmsg,sizeof(int),0);msgrcv(msgqid,&pmsg,256,getpid(),0);printf(“A:receivemsgf

8、rom%d",*((int*)pmsg.mtext));}Elseif(pid==0){signal(2,cancelqueue);msgqid=msgget(75,0777

9、IPC_CREAT);while(1){msgrcv(msgqid,&pmsg,256,1,0);qid=*(int*)pmsg.mtext;print

当前文档最多预览五页,下载文档查看全文

此文档下载收益归作者所有

当前文档最多预览五页,下载文档查看全文
温馨提示:
1. 部分包含数学公式或PPT动画的文件,查看预览时可能会显示错乱或异常,文件下载后无此问题,请放心下载。
2. 本文档由用户上传,版权归属用户,天天文库负责整理代发布。如果您对本文档版权有争议请及时联系客服。
3. 下载前请仔细阅读文档内容,确认文档内容符合您的需求后进行下载,若出现内容与标题不符可向本站投诉处理。
4. 下载文档时可能由于网络波动等原因无法下载或下载错误,付费完成后未能成功下载的用户请联系客服处理。