管道通信机制和消息缓冲机制.docVIP

  • 5
  • 0
  • 约6.42千字
  • 约 14页
  • 2017-06-16 发布于北京
  • 举报
实验题目 管道通信机制和消息缓冲机制 小组合作 否 姓名 班级 学 号 一、实验目的 1、理解和掌握管道通信机制中使用的系统调用命令的格式和如何利用系统调用命令进行进程通信编程。 2、理解和掌握消息缓冲机制中使用的系统调用命令的格式和如何利用系统调用命令进行进程通信编程。 二.实验环境 VMware Workstation工作平台 Linux系统 三、实验内容与步骤 一、管道通信机制 1、无名管道的通信 (1)创建无名管道的格式 #includesys/types.h #includectype.h #includeunistd.h int pipe(int filedes[2]); 正确返回:0;错误返回:-1。 (2)无名管道pipe()的使用 16.1、使用无名管道pipe()进行父子进程之间的通信 源程序代码如下: #includesys/types.h #includectype.h #includeunistd.h int pipe(int filedes[2]); char parent[]=A message to pipecommunication.\n; main() { int pid,chan1[2]; char buf[100]; pipe(chan1); pid=fork(); if(pid0) { printf(to create child error\n); exit(1); } if(pid0) { close(chan1[0]); printf(parent process sends a message to child.\n); write(chan1[1],parent,sizeof(parent)); close(chan1[1]); printf(parent process waits the child to terminate.\n); wait(0); printf(parent process terminate.\n); }else{ close(chan1[1]); read(chan1[0],buf,100); printf(The message read by child process from parent is:%s.\n,buf); close(0); printf(child process terminate\n); } } 实验运行结果如图所示: 2、以命令行为参数的管道通信 (1)命令格式 #includestdio.h #includesys/types.h #includectype.h FiLe popen(const char cmdstring,const char type); (2)打开一个以命令行为参数的管道文件,完成进程之间的通信 16.2、以命令行为参数的管道文件的示例 假设有一个可执行程序chcase,从标准输入设备读字符,将小写字母转换成大写字母并进行输出。主程序使用popen创建管道,实现将某文本文件中的字母转换成大写字母,期中的文本文件名作为参数传进来。 源程序代码如下: #includesys/wait.h #includestdio.h #define MAXLINE 100 int main(int argc,char*argv[]) { char line[MAXLINE]; FILE*fpin,*fpout; if(argc!=2){ fprintf(stderr,usage:a.outpathname\n); exit(1); } if((fpin=fopen(argv[1],r))==NULL) {fprintf(stderr,cant open%s\n,argv[1]); exit(1); } if((fpout=popen(/root/LiFang/chcase.exe,w))==NULL) { fprintf(stderr,popen error\n); exit(1); } while((fgets(line,MAXLINE,fpin))!=NULL) { if(fputs(line,fpout)==EOF){

您可能关注的文档

文档评论(0)

1亿VIP精品文档

相关文档