In this C
program
#include <stdio.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 )
use
dup
instead ofdup2
.dup
creates a alias file descriptor, which value should be always the smallest available file descriptor.new_fd = dup(file);
- In this statementfile
might be having the value3
(becausestdin
is0
,stdout
is1
andstderr
is2
). sonew_fd
will be4
If you want to redirect
stdout
into file. Then do as below.Now dup will return 1 as the alias for the
file
descriptor, because we closedstdout
so opened file descriptors are0,2,3
and1
is smallest available file descriptor.If you are using
dup2
means,dup2(file,1);
- do like thisstdout
is aFILE *
pointer of the standard output stream.dup2
expects file descriptor, also you've messed up the parameters order. Useinstead.
On the better-way-to-do-this part. This way is bad because you probably want to restore your standard output after this
system
call completes. You can do this in a variety of ways. You candup
it somewhere and thendup2
it back (and close thedup
ped one). I personally don't like writing owncat
implementations as suggested in other answers. If the only thing you want is redirecting a single shell command withsystem
to a file in the filesystem, then probably the most direct and simple way is to construct the shell command to do this likeBut you have to be careful if filename (Result) comes from user input as user can supply something like
'Result; rm -rf /*'
as the filename.Also, on the topic of security, you should consider specifying the full path to
ls
as suggested in the comments:The simple thing is to use
>
indeed:An alternative is using
popen()
, something along the lines ofYou should use the
popen()
library function and read chunks of data from the returnedFILE *
and write them to whatever output file you like.Reference.