实验目的:
掌握进程的管道通讯机制。
实验内容:
1.编写一个程序,程序中创建一个子进程,然后父子进程各自独立运行。父进程不断地在标准输入设备上读入小写字母,写入管道。子进程不断地从管道中读取字符,转换为大写字母后输出到标准输出设备上。当读到x时,结束。
2.观察程序输出的结果,并做出合理的解释。
相关的系统调用或函数:fork() pipe() write() read();
程序代码如下:
#include<iostream>
#include<unistd.h> //pipe() 的头文件
#include<sys/types.h> //wait() 的头文件
#include<sys/wait.h> //wait() 的头文件
using namespace std;
int main()
{
int p[2]; //存放管道的读和写两种状态
char inputbuf; //存放输入的字符
char outputbuf; //存放从管道中读取的字符
pid_t pid; //进程
cout<<"please input a lowercase letter ,or input x to exit:"<<endl;
if( pipe(p) == -1){ //创建一个管道 , 创建管道要先于创建子进程
perror("pipe call error!");
return -1;
}
pid = fork(); //创建进程
if( pid > 0 ){ //表示这个是父进程
close(p[0]); //关闭子进程的读取端(P[0]表示)( 读取端 P[1]表示),因为进行写入操作(ps:关闭不是必要的,也可以不用这步,个人要加)
while(1){ //循环读入字符
cin>>inputbuf;
if( inputbuf >= 'a' && inputbuf <= 'z'){ //只要小写字母
write(p[1] , &inputbuf, 1);
}
if( inputbuf == 'x'){ //如果子进程遇到了'x',子进程结束了,父进程才会退出
close(p[1]);
wait(NULL); //父进程才会退出
return 0;
}
}
}else if( pid == 0){ //创建一个子进程
close(p[1]); //关闭子进程的写端,进行读操作
while(1){ //循环从父进程中读取字符
if( read(p[0], &outputbuf , 1) != 0){
if(outputbuf == 'x'){ //如果是‘x’,就退出程序
close(p[0]); //关闭读端
return 0;
}else{
outputbuf -= 32; //转换为大写字母
cout<<outputbuf<<endl;
}
}
}
}else{
cout<<"fork error!"<<endl;
}
return 0;
}