C Program Pipes()

How to Write a C Program Function Pipes() in C Programming Language ?

  1. Create pipes.
  2. Create a pipe and store file descriptors.
  3. Create a child.
  4. Reroute pipe's write end to child's output.
  5. Close unnecessary file descriptors.
  6. Execute the command.
Solution For C Program :


//Create pipes.
int pipes () {
//File descriptor array.
int fd_arr[2];
//Create a pipe and store file descriptors.
pipe(fd_arr);
//Create a child.
pid_t pid = fork();
//Child.
if (pid == 0) {
//Reroute pipe's write end to child's output.
dup2(fd_arr[1], STDOUT_FILENO);
//Close unnecessary file descriptors.
close(fd_arr[0]);
close(fd_arr[1]);
//Execute the command.
if (execvp(command[0], command) == -1) {
exit(EXIT_FAILURE);
}
}
//Parent.
//Set pipes read end to parent's input.
dup2(fd_arr[0], STDIN_FILENO);
//Close unnecessary file descriptors.
close(fd_arr[0]);
close(fd_arr[1]);
//Wait for child.
int status = 0;
waitpid(pid, &status, WUNTRACED);
//Restore I/O.
dup2(INPUT, STDIN_FILENO);
dup2(OUTPUT, STDOUT_FILENO);
return errno;
}


Learn More :