管道通信机制与消息缓冲机制

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

实验题目管道通信机制和消息缓冲机制小组合作

姓名班级

一、实验目的

1、理解和掌握管道通信机制中使用的系统调用命令的格式和如何利用系统调用命令进行进程通信编程。

2、理解和掌握消息缓冲机制中使用的系统调用命令的格式和如何利用系统调用命令进行进程通信编程。

二. 实验环境

1、VMware Workstation工作平台

2、Linux 系统

三、实验内容与步骤一、管道通信机制

1、无名管道的通信

(1)创建无名管道的格式#i nclude

#in cludevct yp e.h> #in cludev uni std.h> int pip e(i nt filedes[2]);

正确返回:0;错误返回:-1。

(2)无名管道pipe ()的使用

16.1、使用无名管道pipe ()进行父子进程之间的通信

源程序代码如下:

#in cludevsys/t yp es.h> #in cludevct yp e.h> #i ncludevu ni std.h> int pip e(i nt filedes[2]);

char paren t[]="A message to pip e'com mun icatio n.\n";

mai n()

int pid,cha n1[2];

char buf[1OO];

pip e(cha n1);

pid=fork();

if(p idvO)

prin tf("to create child error\n");

exit(1);

if(p id>0)

close(cha n1[0]);

pnntf("parent p rocess sends a message to child.\n");

write(cha n1[1], paren t,sizeof( pare nt));

close(cha n1[1]);

printf("parent p rocess waits the child to termi nate.'n");

wait(0);

printf("parent p rocess termi nate.'n");

}else{

close(cha n1[1]);

read(cha n1[0],buf,100);

prin tf("The message read by child p rocess from p are nt is:%s.\rT'buf);

close(0);

prin tf("child p rocess termi nate\ n");

实验运行结果如图所示:

2、以命令行为参数的管道通信

(1)命令格式

#in clude #i nclude #in clude FiLe popen(const char cmdstri ng,c onst char typ e);

(2)打开一个以命令行为参数的管道文件,完成进程之间的通信16.2、以命令行为参数的管道文件的示例

假设有一个可执行程序chcase从标准输入设备读字符,将小写字母

转换成大写字母并进行输出。主程序使用popen创建管道,实现将某文本文件中的字母转换成大写字母,期中的文本文件名作为参数传进来。

源程序代码如下:

#in clude

#in clude

#defi ne MAXLINE 100

int main (i nt argc,char*argv[])

{

char lin e[MAXLINE];

FILE*fpi n, *fpout;

if(argc!=2){

fprin tf(stderr,"usage:a.out

\n");

exit(1);

}

if((fpi n=fopen (argv[1],"r"))==NULL)

{fprin tf(stderr,"ca n't open %s\n",argv[1]); exit(1);

}

if((fpout=popen ("/root/LiFa ng/chcase.exe","w"))==NULL)

{

fpri ntf(stderr," popen error\n"); exit(1);

}

while((fgets(li ne,MAXLINE,fpi n) )!=NULL)

{

if(fputs(li ne,fpout)==EOF){

fprin tf(stderr,"f puts error to pip e.\n"); exit(1);

}

}

if(ferror(fpi n))

{

fpri ntf(stderr,"fgets error.\n");

exit(1);

}

if(p close(fpout)==-1){

fpr in tf(stderr," pciose error.'n");

exit(1);

}

exit(0);

}

实验运行结果如下图所示:

3、有名管道的通信

(1)创建一个有名管道的系统调用mknod() #i nclude #i nclude #i nclude #in cludevfc ntl.h>

int mknod (const char * p ath name,mode_t mode ,dev_t dev);

(2) 打开一个有名管道

open (pathname oflg);

有名管道的使用

16.3 创建有名管道的例子

源程序代码如下:

#in clude

char stri ng[]="this is a exa mple to show fifo com muni cati on"; main( argc,argv)

相关文档
最新文档