2013-10-30 99 views
0
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測試,父線程將運行grep監聽STDIN上的輸入,並且子線程會將ls的輸出寫入STDTOUT。發送一個命令(execv)的輸出到另一個

回答

0

正在使用底層管道/叉是否有必要?如果沒有 - 更簡單的方法 - 使用popen/pclose系統調用。

對於你的例子ls | grep,這是:

FILE *f = popen("ls"); 
char buf[1000]; 
while(fgets(buf, sizeof(buf), f) 
    call_my_grep(buf); 
pclose(f); 

這很容易和高效。

+0

是的我需要使用管道和叉子。 –

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]); 
    } 
} 
相關問題