0

Possible Duplicate:
Is it possible to have pipe between two child processes created by same parent (LINUX, POSIX)

I want to create a program in C. This program has to be able to do the same that piping 2 linux commands do. For Example: ps aux | grep ssh

I need to be able to do this command in a c script.

I know I can use, fork, pipe, exec and dup but I don't quite know how to put them together... Can someone help me with this?

Community
  • 1
  • 1
bryan
  • 31
  • 1
  • 3

1 Answers1

0

As a simple example, this should give you a brief idea of how those system calls work together.

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);
          }
     }
}
Moses Xu
  • 2,140
  • 4
  • 24
  • 35