实验七 管道pipe和popen通信
实验目的1. 掌握无名管道pipe的原理
2. 掌握管道的应用及重定向。
3. 熟悉popen创建管道的方式及应用程序设计;
实验内容
1. (1) 在命令行下执行ls –l |grep .c命令,查看运行结果。
(2)设计一个程序,要求创建一个管道PIPE,复制进程,父进程运行命令“ls -l”,把运行结果写入管道,子进程从管道中读取“ls -l”的结果,把读出的作为输入运行“grep .c”。即实现“ ls –l |grep .c”功能。参考课件ch4 P52,54。
程序源代码:
#include <stdio.h>
#include<signal.h>
#include<unistd.h>
#include<stdlib.h>
int main () {
int fd[2];
char buf[1000];
pid_t p;
if(pipe(fd)<0)
{
printf("创建管道失败");
return -1; }
p=fork();
if(p<0)
{ perror("创建子进程失败");
exit;}
else if (p==0){
close(0);
dup(fd[0]);
execlp("grep","grep",".c",NULL);
}
else{
close(1);
dup(fd[1]);
execlp("ls","ls","-l",NULL);
wait(0);
}
return 0; }
结果截图:
2. (1)在命令行下执行 $touch file.txt $ls –l >file.txt, cat命令查看file.txt内容。
(2)设计一个程序,要求利用popen函数,实现“ls –l > file.txt”的重定向功能,file.txt在程序中创建。参考课件ch4 59
程序源代码:
#include <stdio.h>
#include<signal.h>
#include<unistd.h>
#include<stdlib.h>
int main ()
{ FILE *fp; int num; char buf[500];
memset(buf,0,sizeof(buf));
printf("建立管道……\n");
fp=popen("ls -l","r");
if(fp!=NULL)
{ num=fread(buf,sizeof(char),500,fp);
if(num>0)
{ printf("%s\n",buf); }
pclose(fp); }
else
{ printf("用popen创建管道错误\n");
return 1; }
fp=fopen("a.txt","w+");
fwrite(buf,sizeof(char),500,fp);
pclose(fp);
return 0;
}
运行结果截图: