2011-06-15 144 views
0

可能重複:
Is it possible to have pipe between two child processes created by same parent (LINUX, POSIX)管2 Linux命令

我想創建一個程序C.這個方案必須能夠做同樣的是管道2的Linux命令可以。 例如: ps aux | grep ssh

我需要能夠在c腳本中執行此命令。

我知道我可以使用,forkpipeexecdup,但我不太知道如何把它們放在一起...... 有人可以幫助我?

+0

你走多遠了?你能告訴我們一些你寫的代碼嗎? – 2011-06-15 22:46:54

+0

你只想讓你的程序能夠在管道中工作嗎?然後,只需從'stdin'中讀取並寫入'stdout',就可以自動獲得該行爲。 – 2011-06-15 23:14:03

回答

0

作爲一個簡單的例子,這應該給你一個關於這些系統調用如何協同工作的簡要概念。

void spawn(char *program,char *argv[]){  
    if(pipe(pipe_fd)==0){ 
      char message[]="test"; 
      int write_count=0; 

      pid_t child_pid=vfork(); 

      if(child_pid>0){ 
       close(pipe_fd[0]); //first close the idle end 
       write_count=write(pipe_fd[1],message,strlen(message)); 
       printf("The parent process (%d) wrote %d chars to the pipe \n",(int)getpid(),write_count); 
       close(pipe_fd[1]); 
      }else{ 
       close(pipe_fd[1]); 
       dup2(pipe_fd[0],0); 

       printf("The new process (%d) will execute the program %s with %s as input\n",(int)getpid(),program,message); 
       execvp(program,argv); 
       exit(EXIT_FAILURE); 
      } 
    } 
}