实验题目
管道通信机制和消息缓冲机制
小组合作
否
姓名
班级
学号
一、实验目的
1、理解和掌握管道通信机制中使用的系统调用命令的格式和如何利用系统调用命令进行进程通信编程。
2、理解和掌握消息缓冲机制中使用的系统调用命令的格式和如何利用系统调用命令进行进程通信编程。
VMware Workstation工作平台
Linux系统
三、实验内容与步骤
一、管道通信机制
1、无名管道的通信
(1)创建无名管道的格式
#include<sys/>
#include<>
#include<>
int pipe(int filedes[2]);
正确返回:0;错误返回:-1。
(2)无名管道pipe()的使用
、使用无名管道pipe()进行父子进程之间的通信
源程序代码如下:
#include<sys/>
#include<>
#include<>
int pipe(int filedes[2]);
char parent[]="A message to munication.\n";
main()
{
int pid,chan1[2];
char buf[100];
pipe(chan1);
pid=fork();
if(pid<0)
{
printf("to create child error\n");
exit(1);
}
if(pid>0)
{
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)命令格式
#include<>
#include<sys/>
#include<>
FiLe popen(const char cmdstring,const char type);
(2)打开一个以命令行为参数的管道文件,完成进程之间的通信
、以命令行为参数的管道文件的示例
假设有一个可执行程序chcase,从标准输入设备读字符,将小写字母转换成大写字母并进行输出。主程序使用popen创建管道,实现将某文本文件中的字母转换成大写字母,期中的文本文件名作为参数传进来。
源程序代码如下:
#include<sys/>
#include<>
#define MAXLINE 100
int main(int argc,char*argv[])
{
char line[MAXLINE];
FILE*fpin,*fpout;
if(argc!=2){
fprintf(stderr,"usage:<pathname>\n");
exit(1);
}
if((fpin=fopen(argv[1],"r"))==NULL)
{fprintf(stderr,"can't open%s\n",argv[1]);
exit(1);
}
if((fpout=popen("/root/LiFang/","w"))==NULL)
{
fprintf(stderr,"popen error\n");
exit(1);
}
while((fgets(line,MAXLINE,fpin))!=NULL)
{
if(fputs(line,fpout)==EOF){
fprintf(stderr,"fputs error to pipe.\n");
exit(1);
}
}
管道通信机制和消息缓冲机制 来自淘豆网m.daumloan.com转载请标明出处.