Skip to content
Advertisement

Redirect the standard output [closed]

Hello and thank you for attention. I am writing my own shell in c and i have problem with redirect the standard output. For example, I get command: ls -l >> file and I need to display output to file. Can you give me some ideas to resolve that problem? Thanks.

Advertisement

Answer

You may want to use dup() & dup2(), here are two functions I have ready:

void stdout_redirect(int fd, int *stdout_bak)
{
  if (fd <= 0)
    return;
  *stdout_bak = dup(fileno(stdout));
  dup2(fd, fileno(stdout));
  close(fd);
}

void stdout_restore(int stdout_bak)
{
  if (stdout_bak <= 0)
    return;
  dup2(stdout_bak, fileno(stdout));
  close(stdout_bak);
}

Here is how to use it:

int main(void)
{
  int stdout_bak;
  FILE *fd;

  fd = fopen("tmp", "w");
  stdout_redirect(fileno(fd), &stdout_bak);
  /* Your Stuff Here */
  stdout_restore(&stdout_bak);
  return 0;
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement