I have a problem when I used dup2
direct stdout
first to a temporal file, and after to a common file. This is a portion my code:
FILE* fdArch=fopen("file.txt","w");
char nameBuff[100];
memset(nameBuff,0,sizeof(nameBuff));
strncpy(nameBuff,"/tmp/myTmpFile-XXXXXX",sizeof("/tmp/myTmpFile-XXXXXX"));
int fdNewFile=mkstemp(nameBuff);
if(fdNewFile==-1){
perror("error creating temporal file");
}
dup2(fdNewFile,STDOUT_FILENO);
read(fd[0], readbuffer, sizeof(readbuffer));
char *argv[]={ "/home/user/workspace/CProgram/Debug/program", readbuffer, NULL};
execv(argv[0],argv);
close(fdNewFile);
dup2(fileno(fdArch),STDOUT_FILENO);
char *argv1[]={"/usr/bin/sort",nameBuff, NULL};
execv(argv1[0],argv1);
fclose(fdArch);
unlink(nameBuff);
I run an external program called program and the out is redirected with dup2
to a temporal file, well this works fine, but after when I redirect with dup2
the stdout
to fdArch
and run sort over the temporal file, the out is not redirected to fdArch
.
Is there an error of concept or something is missing?
Your usage of
dup2()
is fine, but you do have a major error: theexecv()
function does not return, except when it fails. It, and all the other functions in its family, replace the program in which it is called with the one specified. Thus, in fact you never do redirectstdout
a second time or run/bin/sort
. If you want to do those things, then you shouldfork()
, perform theexecv()
in the child process, and have the parentwait()
for it to complete before continuing.