2011-06-15 61 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); 
      } 
    } 
}