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.
Asked
Active
Viewed 47 times
-2
-
1have you heard of [dup2](http://man7.org/linux/man-pages/man2/dup.2.html) – Seek Addo Apr 14 '17 at 20:12
-
1Possible duplicate of [Rerouting stdin and stdout from C](http://stackoverflow.com/questions/584868/rerouting-stdin-and-stdout-from-c) – Support Ukraine Apr 14 '17 at 20:13
-
Yes, I have heard about it but I don t know how it exactly work. I read about it but i don t know how to use it – ByQ Apr 14 '17 at 20:17
-
@ByQ The man page explain it all and provides some example work. What do you mean you don't know how to use it. – Seek Addo Apr 14 '17 at 20:52
1 Answers
0
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;
}

Ra'Jiska
- 979
- 2
- 11
- 23