Skip to content

Instantly share code, notes, and snippets.

@sromano
Created April 19, 2017 17:51
Show Gist options
  • Save sromano/93b968ad2e72e9f63f9c6ae2b180ef33 to your computer and use it in GitHub Desktop.
Save sromano/93b968ad2e72e9f63f9c6ae2b180ef33 to your computer and use it in GitHub Desktop.
Ejemplo para ejecutar ls | wc -l
#include <stdio.h>
#include <unistd.h>
//Ejemplo para ejecutar ls | wc -l
int main( int argc, char *argv[], char *env[] )
{
pid_t child_pid;
int pipe_fd[2];
//obtengo el número del file descriptor de stdin y de stdout
//(manera elegante para no poner 0 y 1 hardcodeado)
int STDOUT = fileno(stdout);
int STDIN = fileno(stdin);
//Inicializo el pipe
if(pipe(pipe_fd) == -1){
perror("problema en pie");
_exit(1);
}
//Creo el proceso hijo
if((child_pid = fork()) < 0 )
{
perror("problema en fork");
_exit(1);
}
//Si soy hijo, ejecuto ls
if(child_pid == 0){
//Cierro el extremo de lectura del pipe en el hijo
close(pipe_fd[0]);
//Conecto stdout al extremo de escritura del pipe
if(dup2(pipe_fd[1],STDOUT) == -1){
perror("no anduvo el dup2 del hijo");
}
//Cambio el código a ls
execlp("ls", "ls", 0, 0);
perror("no anduvo el exec del hijo");
_exit(1);
}
//Si soy padre, ejecuto wc
else{
//Cierro el extremo de escritura del pipe en el padre
close(pipe_fd[1]);
//Conecto stdin al extremo de lectura del pipe
if(dup2(pipe_fd[0],STDIN) == -1){
perror("no anduvo el dup2 del padre");
}
//Cambio el código a wc
execlp("wc", "wc", "-l", 0, 0);
perror("no anduvo el exec del padre");
_exit(1);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment