Home > OS >  Dup redirected back problem
Dup redirected back problem

Time:10-27

 
Int fd1=open (argv [1], O_RDWR | O_CREAT, 0644);
If (fd1==1)
{
Perror (" open file failed \ n ");
exit(0);
}
Int cpFd=dup (STDOUT_FILENO);
If (cpFd==1)
{
Perror (" dup failed \ n ");
exit(0);
}
Int newFd=dup2 (fd1 STDOUT_FILENO);
If (newFd==1)
{
Perror (" dup2 failed \ n ");
exit(0);
}
Printf (" dup2 test \ n ");
Printf ("... \n");
Close (fd1);

CpFd=dup2 (cpFd, STDOUT_FILENO);
If (cpFd==1)
{
Printf (" restore failed \ n ");
exit(0);
}
Printf (" restore out \ n ");

Code as above, the idea is to use the dup copy a standard output file descriptors, and then standard output to an open file, ended, and then use the saved file descriptor to the standard output of healing,
Problem is the use of the dup function after all the printf function output to standard output, not redirected to a file, if change the printf to write functions can success again, do not use the dup replicate, so all the printf redirect output to file,
Excuse me what reason be?


  • Related