首页 > 解决方案 > 如何在 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);
}

标签: cpipeio-redirection

解决方案


推荐阅读