这里我使用无名管道
知识点:
1. 管道pipe
2. 创建子进程fork
3. 重定向dup2
4. exec函数族execlp
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
/**
* 功能:使用管道实现ls -l | wc -w,显示单词数量
* @author AWEEN
* @create on 2018-06-03
*/
int main(void){
int fd[2];
//新建无名管道
int ret = pipe(fd);
if(ret < 0){
perror("管道创建失败");
exit(1);
}
//创建子进程
pid_t pid = fork();
if(pid < 0){
perror("子进程创建失败 ");
exit(1);
}
//子进程用于写操作
if(pid == 0){
//关闭读端
close(fd[0]);
//将标准输出重定向到写管道
dup2(fd[1],1);
if((execlp("ls","ls","-l",NULL)) < 0){
perror("execlp失败");
exit(1);
}
exit(1);
}
//主进程用于读操作
if(pid > 0){
//关闭写端
close(fd[1]);
//将标准输入重定向到读管道
dup2(fd[0],0);
if(execlp("wc","wc","-w",NULL) < 0){
perror("execlp失败");
exit(1);
}
exit(1);
}
return 0;
}

本文介绍如何通过无名管道实现两个进程间的通信,具体实现了ls-l命令输出文件详细信息后,通过wc-w统计单词数量的功能。文章通过C语言编程,详细展示了使用pipe创建管道、fork创建子进程、dup2进行文件描述符重定向以及execlp执行外部命令的过程。

被折叠的 条评论
为什么被折叠?



