jiankeabcd
2017-07-09 02:34使用C语言实现Linux管道符命令
例如
uniq < tmp.txt | wc -l
其中 tmp.txt为
0
0
1
1
1
2
0
2
可以使用fork, exec族群, pipe, dup, dup2, open, close的系统调用
不能直接使用execlp执行上述命令
我的想法是利用pipe实现单向管道,父进程使用exec执行uniq < txt,
执行后为
0
1
2
0
2
并将此标准输出用dup2替换为标准输入,进入子进程。子进程执行wc -l之后利用父进程的标准输入得到结果5
自己写的代码如下 但是无法正确输出 望高人解答
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc, char const *argv[]){
int fd[2];
pid_t pid;
pipe(fd);
if((pid = fork()) == 0){/* child process */
close(fd[1]);
execlp("wc", "wc", "-l", "fd[1]", NULL);
close(fd[0]);
}
else{/* parent process */
close(fd[0]);
dup2(0, 1);
close(0);
fd[1] = open("tmp.txt", O_RDONLY);
execlp("uniq", "uniq", "tmp.txt", NULL);
close(fd[1]);
}
}
- 点赞
- 回答
- 收藏
- 复制链接分享
1条回答
为你推荐
- 使用C语言实现Linux管道符命令
- c
- linux
- c++
- 操作系统
- unix
- 1个回答