c - 如何在 Lunux 中使用 C 编写重定向代码?
问题描述
我的功课是用 C 让这句命令在 Linux 中工作
“猫 /etc/passwd | 剪切 -d : -f 1 > userlist.txt”
我只需要使用 dup2()、execl()、mkfifo、pipe() 函数来完成这个作业。
我可以完成
“猫 /etc/passwd | 剪切 -d : -f 1”
成功地。
pid_t pid;
int pipefd[2] = {0, };
if (pipe(pipefd) == -1) {
perror("pipe() error!");
return -1;
}
pid = fork();
if (pid == -1) {
perror("fork() error!");
}
else if (pid == 0) { // Child
close(pipefd[0]);
dup2(pipefd[1], STDOUT_FILENO);
execl("/bin/cat", "cat", "/etc/passwd", NULL);
}
else { // Parent
close(pipefd[1]); // close unused write end
wait(&pid);
dup2(pipefd[0], STDIN_FILENO);
execl("/usr/bin/cut", "cut", "-d", ":", "-f", "1", NULL);
}
解决方案
推荐阅读
- php - 如何使用php从csv文件中动态获取列值
- javascript - 使用 forEach 循环在一个数字范围内循环,并将任何包含整数 1 的数字替换为“Beep”
- vb.net - VB.NET 数据库事务不去数据库
- sql - 旧作业和新作业列 SQL
- reactjs - react-hook-form 版本 7 验证错误不起作用
- python - 有没有办法使用 Python 在 docx 文件上将图像换行设置为“通过”?
- excel - 基于动态范围创建数据透视表
- node.js - Google Cloud Storage NodeJS 多个读取请求加载太慢
- string - 硬编码字符串变为粗体
- powershell - 点源文件低于一级?