Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

245
Vistas
can not read from pipe with execlp

For an assignment, i am supposed to implement the linux terminal. My terminal should support arguments with pipes. Like the user can input: ls | grep ".cpp" What i have done so far is:

pid = fork();
if(pid==0)
{
  close(fd[0]);
  dup2(fd[1],1);
  close(fd[1]);
  execlp("/bin/ls","ls");
}
wait(NULL);
pid=fork();
if(pid==0)
{
  close(fd[1]);
  dup2(fd[0],0);
  close(fd[0]);
  execlp("/bin/grep","grep",".cpp");
}

my first child works perfectly, writes the output of ls into a pipe declared earlier, however, my second child runs grep, but it apparently can not get input from pipe. Why is that so? when i run it, my output is /root/OS $ ls | grep

it just gets stuck like this

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Don't ignore compiler warnings:

$ gcc lol.c
lol.c: In function ‘main’:
lol.c:14:5: warning: not enough variable arguments to fit a sentinel [-Wformat=]
     execlp("/bin/ls","ls");
     ^
lol.c:23:5: warning: missing sentinel in function call [-Wformat=]
     execlp("/bin/grep","grep",".cpp");
     ^

Here's man execlp:

The first argument, by convention, should point to the filename associated with the file being executed. The list of arguments must be terminated by a NULL pointer, and, since these are variadic functions, this pointer must be cast (char *) NULL.

Always compile with -Werror so that compilation fails if there are warnings, and preferably also with -Wall to get warnings for all potential issues.

Here's your program with a main method and sentinels added:

#include <unistd.h>
#include <sys/wait.h>


int main() {
  int fd[2];
  int pid;

  pipe(fd);
  pid = fork();
  if(pid==0)
  { 
    close(fd[0]);
    dup2(fd[1],1);
    close(fd[1]);
    execlp("/bin/ls","ls", NULL);
  }
  wait(NULL);
  pid=fork();
  if(pid==0)
  { 
    close(fd[1]);
    dup2(fd[0],0);
    close(fd[0]);
    execlp("/bin/grep","grep",".cpp", NULL);
  }
  return 0;
}

Here's how it runs now:

$ gcc -Wall -Werror lol.c -o lol
$ ./lol
foo.cpp
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda