Link to home
Start Free TrialLog in
Avatar of libin_v
libin_vFlag for India

asked on

How do U do redirection?

How do I get this code to redirect the output of ls to list.txt
/*
      check for redirection
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>

int main()
{
      pid_t pid;
      int status;

      pid = fork();

      if (pid == 0)
      {
            int stdout = open ("list.txt", O_RDONLY);
            dup2 (stdout, STDOUT_FILENO);
            close (stdout);
            execl ("\\bin\\ls", "ls", NULL);
      }
      if (pid == -1)
            printf ("Error\n");
      else
            waitpid(pid, &status, 0);
}
Avatar of baboo_
baboo_

execl ("\\bin\\ls", "ls", , ">> list.txt", NULL);

maybe...  I don't know if that's ok...

baboo_
ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
call to open()  is wrong

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

int main()
{
     pid_t pid;
     int status;

     pid = fork();

     if (pid == 0)
     {
          int stdout = open ("list.txt", O_WRONLY | O_CREAT); // use this
          dup2 (stdout, STDOUT_FILENO);
          close (stdout);
          execl ("\\bin\\ls", "ls", NULL);
     }
     if (pid == -1)
          printf ("Error\n");
     else
          waitpid(pid, &status, 0);
}