/*7.“grep –o”不会输出包含某字符串的行,而只会把匹配的字符串输出(有几个匹配就输出几次,且每行输出一个匹配字符串),
因而可以用 “grep –o xxx file | wc -l”来统计文件file中“xxx”字符串出现了多少次。
请用多进程pipe程序实现该功能(此前先用which命令查一下grep命令和wc命令在哪个目录),
要求:创建一个文本文件为zhangsan,自己在该文件中输入若干数目的字符串“zhangsan”,将其作为操作的原材料。
*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<sys/stat.h>
#include<unistd.h>
#define MSGSIZE 24
int main(int argc,char *argv[])
{
int status;
int pid[2],pipe_fd[2];
char *prog1_argv[]={"/bin/grep","-o",argv[1],argv[2],NULL};
char *prog2_argv[]={"/usr/bin/wc","-l",NULL};
//create the pipe
if(pipe(pipe_fd)<0)
{
perror("pipe failed\n");
exit(errno);
}
//兄弟之间管道
if((pid[0]=fork())<0)
{
perror("fork failed\n");
exit(errno);
}
//pid[0]==0,即进入子进程
if(!pid[0])
{
close(pipe_fd[0]);
dup2(pipe_fd[1],1);//pipe_fd[1]指向STDOUT_FILENO,即输出重定向
close(pipe_fd[1]);
//装载一个新的程序,并将其转换到调用进程的内存空间,也即向管道写入
execvp(prog1_argv[0],prog1_argv);
}
//回到父进程
if(pid[0])
{
if((pid[1]=fork())<0)
{
perror("fork failed\n");
exit(errno);
}
if(!pid[1])
{
close(pipe_fd[1]);
dup2(pipe_fd[0],0);//pipe_fd[0]指向STDIN_FILENO,即输入重定向
close(pipe_fd[0]);
//装载一个新的程序,并将其转换到调用进程的内存空间,也即向管道写入
execvp(prog2_argv[0],prog2_argv);
}
close(pipe_fd[0]);
close(pipe_fd[1]);
waitpid(pid[0],&status,0);
waitpid(pid[1],&status,0);
}
return 0;
}
友情链接:
(1)UNIX管道应用及Shell实现(一)-主体框架
https://blog.youkuaiyun.com/crazy_scott/article/details/79548331
(2)UNIX管道应用及Shell实现(二)-命令解析
https://blog.youkuaiyun.com/crazy_scott/article/details/79548325
(3)Linux–实现一个简易的Shell(可以获取命令提示符,支持管道)
https://blog.youkuaiyun.com/xu1105775448/article/details/80311274
(4)Linux进程间通信(二)—管道通信之无名管道及其基础实验
https://blog.youkuaiyun.com/mybelief321/article/details/9073895
(5)Linux进程间通信(三)—管道通信之有名管道及其基础实验
https://blog.youkuaiyun.com/mybelief321/article/details/9075229
(6)Linux进程间通信(九)—综合实验之有名管道通信实验
https://blog.youkuaiyun.com/mybelief321/article/details/9196629