Skip to content

Instantly share code, notes, and snippets.

@dimkouv
Created December 11, 2017 23:59
Show Gist options
  • Save dimkouv/9d163650acb17bd086f90beb47d9cf0e to your computer and use it in GitHub Desktop.
Save dimkouv/9d163650acb17bd086f90beb47d9cf0e to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#include <fcntl.h>
// counts files on the current directory
// linux equivalent "ls -l | wc -l"
int main() {
int pipes[2];
pipe(pipes); // create pipe
if (fork() == 0) { // child
close(pipes[0]); // disable reading to pipe
int bak = dup(STDOUT_FILENO); // backup stdout
dup2(pipes[1], STDOUT_FILENO); // set stdout to pipe (write everything printed on pipe)
execl("/bin/ls", "ls", NULL); // call ls (output will be writtern on pipe)
dup2(bak, STDOUT_FILENO); // restore stdout from backup
}
else { // parent
close(pipes[1]); // disable writing to pipe from parent
int bak = dup(STDIN_FILENO); // backup stdin
wait(NULL); // wait for child to complete
dup2(pipes[0], STDIN_FILENO); // set stdin to pipe (read ls output)
execl("/usr/bin/wc", "wc", "-l", NULL); // execute wc with standard input from pipe
close(pipes[0]); // close pipe
dup2(bak, STDIN_FILENO); // restore stdin to keyboard
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment