操作系统实验进程的通信.docVIP

  • 18
  • 0
  • 约5.23千字
  • 约 7页
  • 2017-01-30 发布于重庆
  • 举报
操作系统实验进程的通信

(操作系统原理和linux操作系统相结合的实验) 实验二 进程的通信 一 实验目的 1 学会使用vi编辑器编辑C语言程序 2 学会Linux环境下gcc的使用 3 学会调试工具GDB的使用 二 实验原理 1 利用linux提供的进程通信的系统调用设计进程通信程序,加深对进程通信概念的理解。 2 体会进程通信的方法和效果。 三 实验环境 PC机1台,Windows操作系统和其上的虚拟Linux操作系统。 四 实验步骤 1. 管道通信 (1)编写一个程序。父进程创建一个子进程和一个无名管道fd,由子进程向管道写入信息“This is a message”,然后终止执行;父进程接收到子进程终止信号后从管道中读出并显示信息后结束。 #includestdio.h #includeunistd.h main() { int p1,fd[2]; char outpipe[50]; //定义读缓冲区 char inpipe[50]=This is a message!; //定义写缓冲区 pipe(fd); //创建无名管道fd while((p1=fork())==-1); if (p1==0) //子进程返回 { write(fd[1],inpipe,50); //写信息到管道 exit(0); } else //父进程返回 { wait(0); //等待子进程终止 read(fd[0],outpipe,50); //从管道读信息到读缓冲区 printf(%s\n,outpipe); //显示读到的信息 exit(0); } } (2)父进程创建两个子进程,父子进程之间利用管道进行通信。要求能显示父进程、子进程各自的信息,体现通信效果。(源程序pipe_1.c) #includestdio.h main() { int I,r,j,k,l,p1,p2,fd[2]; char buf[50],s[50]; pipe(fd); while((p1=fork())==-1); if(p1==0) { lockf(fd[1],1,0); sprintf(buf,Child process p1 is sending message!\n); printf(Child process p1!\n); write(fd[1],buf,50); lockf(fd[1],0,0); sleep(5); j=getpid(); k=getppid(); printf(p1 %d is weakup.My parent process id is %d.\n,j,k); exit(0); } else { while((p2=fork())==-1); if(p2==0) { lockf(fd[1],1,0); sprintf(buf,Child process p2 is sending message!\n); printf(Child process p2!\n); write(fd[1],buf,50); lockf(fd[1],0,0); sleep(5); j=getpid(); k=getppid(); printf(p2 %d is weakup.My parent process id is %d.\n,j,k); exit(0); } else { I=getpid(); wait(0); if(r=read(fd[0],s,50)==-1) printf(can’t read pipe.); else printf(Parent %d:%s\n,l,s); wait(0); if(r=read(fd[0],s,50)==-1) prin

文档评论(0)

1亿VIP精品文档

相关文档