How to Write a C Program Function Pipes() in C Programming Language ?
- Create pipes.
- Create a pipe and store file descriptors.
- Create a child.
- Reroute pipe's write end to child's output.
- Close unnecessary file descriptors.
- 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 :
Example
- C Program String - Alphabet Count Example
- C Program Array Example: Average
- C Program Array Example: Reverse
- C Program Switch - Case Example
- C Program if - else if - else Example
- C Program Friend & Operator: Point2D Example
- C Program Friend & Operator: Vector Example
- C Program Recursion Example
- C Program Structure Example-2
- C Program Structure Example
- C Program Pointer Example
- C Program Function Example
- C Program String Example
- C Program Character Example
- C Program sizeof & memcpy Example
- C Program Array Example
- C Program Side Length Example
- C Program 0-1000 to Ordinary
- C Program Roboturtle
- C Program to Destroys a Mailbox
- C Program to Destroys a semaphore
- C Code for Testing the pH Meter V1.0
- APA 102c test program
- How To Retarget the C Library printf function to the UART.