Redirect to execlp()

910 views Asked by At

I have a problem with execlp. When I do not know how to redirect command from arrays of pointers to execlp correctly. For example i want to use

ls -l | sort -n

my program takes only "ls" and "sort"

      int pfds[2];
      pipe(pfds);
      child_pid = fork();
      if(child_pid==0)
      {       
        close(1);
            dup(pfds[1]);   
            close(pfds[0]); 
            execlp(*arg1, NULL);

      }
      else 
      {
        wait(&child_status); 
            close(0);
        dup(pfds[0]);
        close(pfds[1]); 
            execlp(*arg2, NULL);
      }

All commands are in arrays of pointers where: ls -l is in first table and sort -n in second

1

There are 1 answers

1
Marian On

You probably wanted to use dup2 to redirect stdin and stdout. Also you are not using execlp correctly. It expects variable number of parameters terminated by NULL pointer. And as suggested by comments, the wait command shall not be there.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main() {
    int pfds[2];
    pipe(pfds);
    int child_pid;
    child_pid = fork();
    if(child_pid==0)
    {       
        dup2(pfds[1], 1);   
        close(pfds[0]); 
        execlp("ls", "-al", NULL);

    }
    else 
    {
        dup2(pfds[0], 0);
        close(pfds[1]); 
        execlp("sort", "-n", NULL);
    }
}