将一个命令(execv)的输出发送到另一个命令
例如,如果我想做与ls | grep测试等效的测试,父线程将运行grep侦听STDIN上的输入,子线程将ls的输出写入STDTOUT。是否需要使用低级管道/分叉?如果没有-更简单的方法-使用popen/pclose系统调用 以ls | grep为例,如下所示:将一个命令(execv)的输出发送到另一个命令,c,piping,execv,C,Piping,Execv,例如,如果我想做与ls | grep测试等效的测试,父线程将运行grep侦听STDIN上的输入,子线程将ls的输出写入STDTOUT。是否需要使用低级管道/分叉?如果没有-更简单的方法-使用popen/pclose系统调用 以ls | grep为例,如下所示: void execute_command_pipe(char * command_from, char * command_to, char ** args_from, char ** args_to) { pipe(pipefd
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]);
}
}
这既简单又有效。是的,我需要使用管道和叉子。
FILE *f = popen("ls");
char buf[1000];
while(fgets(buf, sizeof(buf), f)
call_my_grep(buf);
pclose(f);
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]);
}
}