unix实验报告7

 实验 七

 管道 e pipe 和 和 n 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; } 运行结果截图: