[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 961
  • Last Modified:

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);
}
0
libin_v
Asked:
libin_v
1 Solution
 
baboo_Commented:
execl ("\\bin\\ls", "ls", , ">> list.txt", NULL);

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

baboo_
0
 
ozoCommented:
/*
     check for redirection
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>

int main()
{
     pid_t pid;
     int status;

     pid = fork();

     if (pid == 0)
     {
          int out = open ("list.txt", O_WRONLY|O_CREAT,0644);
          if( out <0 ){ perror("list.txt"); exit(errno); }
          dup2 (out, fileno(stdout));
          execl ("/bin/ls", "ls", NULL);
     }
     if (pid == -1)
          printf ("Error\n");
     else
          waitpid(pid, &status, 0);
}
0
 
van_dyCommented:
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);
}
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now