Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将一个命令(execv)的输出发送到另一个命令_C_Piping_Execv - Fatal编程技术网

将一个命令(execv)的输出发送到另一个命令

将一个命令(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

例如,如果我想做与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);

    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]);
    }
}