我的功课是使用C在Linux中使此命令句子生效
“ cat / etc / passwd | cut -d:-f 1> userlist.txt”
我只需要使用dup2(),execl(),mkfifo,pipe()函数即可完成此作业。
我能完成
“ cat / etc / passwd | cut -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);
}
为什么使事情变得不必要的复杂?可以做到:
#include <stdlib.h>
int main(void)
{
system("cat /etc/passwd | cut -d : -f 1 > userlist.txt");
}