void execute_command_pipe(char * command_from, char * command_to, char ** args_from, char ** args_to) {
pipe(pipefd);
int pid = fork();
close(pipefd[0]);
if (pid == 0) {
//close(STDOUT_FILENO);
dup2(pipefd[1], STDOUT_FILENO);
int rv1 = execv(get_contain_dir(command_from), args_from);
close(pipefd[1]);
} else {
close(pipefd[1]);
dup2(pipefd[0], STDIN_FILENO);
int rv2 = execv(get_contain_dir(command_to), args_to);
close(pipefd[0]);
}
}
例如,如果我想做相当于ls | grep test,父线程将运行grep侦听STDIN上的输入,子线程将ls的输出写入STDTOUT。
答案 0 :(得分:0)
是否需要使用低级管/叉?如果没有 - 更简单的方法 - 使用popen / pclose系统调用。
以ls |为例grep,这是:
FILE *f = popen("ls");
char buf[1000];
while(fgets(buf, sizeof(buf), f)
call_my_grep(buf);
pclose(f);
这很简单有效。
答案 1 :(得分:0)
void execute_command_pipe(char * command_from, char * command_to, char ** args_from, char ** args_to) {
pipe(pipefd);
int pid = fork();
if (pid != 0) {
dup2(pipefd[0], STDIN_FILENO);
close(pipefd[0]);
int rv2 = execv(get_contain_dir(command_to), args_to);
} else {
dup2(pipefd[1], STDOUT_FILENO);
close(pipefd[1]);
int rv1 = execv(get_contain_dir(command_from), args_from);
close(pipefd[0]);
}
}