In this C
program
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
int main()
{
int file = open("Result", O_CREAT|O_WRONLY, S_IRWXU);
dup2(stdout, file);
system("ls -l");
return 0;
}
I'm trying to redirect the output of system() to a file, for that i have used dup2 but it is not working.
What's wrong with this code?
and, please tell me if there is any better way to do this? (without using >
at the terminal )
>
redirection in thesystem
command? – Boxcarsystem("ls -l > Result");
or make your ownfork()
/exec*()
combination. – Simiansystem
. It's always wrong. Run the child process yourself without a shell, either usingfork
andexecvp
orposix_spawn
. – Hestasystem
should be considered deprecated because (1) it's hard to do anything useful to it, and (2) trying to do anything useful with it (e.g. passing arguments) almost certainly creates dangerous (potentially security-critical) bugs related to shell escaping. – Hesta