资源描述:
《操作系统实验进程的通信》由会员上传分享,免费在线阅读,更多相关内容在学术论文-天天文库。
1、(操作系统原理和linux操作系统相结合的实验)实验二进程的通信-实验目的1学会使用Vi编辑器编辑C语言程序2学会Linux环境Kgcc的使用3学会调试工具GDB的使用二实验原理1利用lirmx提供的进程通信的系统调用设计进程通信程序,加深对进程通信概念的理解。2体会进程通信的方法和效果。三实验环境PC机1台,Windows操作系统和其上的虚拟Linux操作系统。四实验步骤1.管道通信(1)编写一个程序。父进程创建一个子进程和一个无名管道fd,由子进程向管道写入信息"Thisisamessage",然后终
2、止执行;父进程接收到子进程终止信号后从管道中读出并显示信息后结束。#include#includemain(){intpl,fd[2];charoutpipe[50];//定义读缓冲区charinpipe[50]="Thisisamessage!";//定义写缓冲区pipe(fd);//创建无名管道fdwhile((pl=fork())==-l);if(pi==0)//子进程返回{write(fd[1],inpipe,50);//写信息到管道exit(O);else/
3、/父进程返Mwait(O);//等待子进程终止read(fd[0],outpipe,50);//从管道读信息到读缓冲区printf("%s",outpipe);//显示读到的信息exit(O);[root@locaIhostpub]#gccpipe.c-opipe[root@locaIhostpub]#,/pipeThisisanrssage![root@locaIhostpub]#(2)父进程创建两个子进程,父子进程之间利用管道进行通信。要求能显示父进程、子进程各自的信息,体现通信效果。(源程序pi
4、pe_l.c)#inckide<$tdio.h>main(){intI,r,j,k,l,pl,p2,fd[2];charbuf[50],$[50];pipe(fd);while((pl=fork())==-l);if(pl==O){lockf(fd[l],l,0);sprintf(buf,"Childprocesspiissendingmessage!");printf("Childprocesspi!");write(fd[l],buf,50);lockf(fd[l],0,0);sleep(5)
5、;j=getpid();k=getppid();printff’pl%disweakup.Myparentprocessidis%d.M,j,k);exit(O);}else{while((p2=fork())==-1);if(p2==O){lockf(fd[l],l,0);sprintf(buf,"Childprocessp2issendingmessage!M);printf(”Childprocessp2!");write(fd[1],buf,50);lockf(fd[l],0,0);s
6、leep(5);j=getpid();k=getppid();printf(’’p2%disweakup.Myparentprocessidis%d.’’,j,k);exit(O);}else{I=getpid();wait(O);if(r=read(fd[O],s,5O)==-1)printf(ncan’treadpipe.’’);elseprintf("Parent%d:%s",l,s);wait(O);if(r=read(fd10],s,50)==-1)printff’can’treadpi
7、pe’’);elseprintf("Parent%d:%s",l,$);exit(O);})}-opipe」-opipe」结果:[root@IocaIhost[root@IocaIhost[root@IocaIhostpub]#gccpipe」.cpub]#gccpipe」.cpub]#./pipe一1ChiIdprocesspi!ChiIdprocessp2!pi17164isveakupparentprocessidis17163.Parent134513609:QiiIdprocesspiis
8、sendingiirssage!p217165isveakupparentprocessidis17163.Parent134513609:QiiIdprocessp2issendingiirssage![root@IocaIhostpub]#2.共享内存通信。编程实现消息的发送与接收:发送进程将要发送的消息从键盘输入,每输入一行就作为一条消息发送,用“end”作为结束消息。(源代码:sndshm.c)接收进程从消息队列上逐