Skip to content

Instantly share code, notes, and snippets.

@panta
Created January 31, 2022 17:28
Show Gist options
  • Save panta/971c6ccee1c6645adb917815d673d35e to your computer and use it in GitHub Desktop.
Save panta/971c6ccee1c6645adb917815d673d35e to your computer and use it in GitHub Desktop.
Command pipe example in C - execute "ls / | wc -l"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
int main(void) {
/* set up pipe. */
int pfd[2];
if (pipe(pfd) < 0) {
perror("pipe()");
exit(1);
}
/* fork a child process and let it execute the grep command. */
pid_t child_pid;
if ((child_pid = fork()) == 0) {
/* CHILD PROCESS */
/* redirect child stdout to pipe */
if (dup2(pfd[1], STDOUT_FILENO) == -1) {
perror("dup2() in child");
exit(1);
}
/* remove the file descriptors for the pipe from the child’s */
/* file descriptor table. */
if (close(pfd[0]) < 0) {
perror("close() read end of pipe in child");
exit(1);
}
if (close(pfd[1]) < 0) {
perror("close() write end of pipe in child");
exit(1);
}
/* exec the first command of the pipe */
execlp("ls", "ls", "/", NULL);
/* if the following statement is reached, execlp must have failed. */
perror("execlp() in child");
exit(1);
}
else {
/* PARENT PROCESS */
/* make sure that fork worked. */
if ((int)child_pid < 0) {
perror("fork() failed");
exit(1);
}
/* redirect parent stdin to pipe and exec the wc command. */
if (dup2(pfd[0], STDIN_FILENO) == -1) {
perror("dup2() in parent");
exit(1);
}
/* remove the file descriptors for the pipe from the parent’s */
/* file descriptor table. */
if (close(pfd[0]) < 0) {
perror("close() read end of pipe in parent");
exit(1);
}
if (close(pfd[1]) < 0) {
perror("close() write end of pipe in parent");
exit(1);
}
/* exec the wc command. */
execlp("wc", "wc", "-l", NULL);
/* if the following statement is reached, execlp must have failed. */
perror("execlp in parent");
exit(1);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment