This is a sample about how to redirect and restore STDOUT on unix platform.
Sometimes, we may need to redirect STDOUT to a file, and restore back later.
This sample program is verified on Linux
The source program:
$ cat t.c
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int mOldStdout = -1;
int mNewStdout = -1;
void dupOutput(char * filename)
{
mNewStdout = open(filename, O_CREAT|O_WRONLY|O_APPEND|O_SYNC, S_IRWXU|S_IRWXG|S_IROTH);
mOldStdout = dup(STDOUT_FILENO);
fsync(STDOUT_FILENO);
dup2(mNewStdout, STDOUT_FILENO);
}
void restoreOutput()
{
fsync(STDOUT_FILENO);
dup2(mOldStdout, STDOUT_FILENO);
close(mOldStdout);
close(mNewStdout);
}
int main(int argc, char * argv[]) {
printf("IN STDOUT-1\n");
dupOutput("logfile");
printf("IN LOGFILE-1\n");
restoreOutput();
printf("IN STDOUT-2\n");
}
Compile and execute the program
$ rm -f logfile
$ gcc t.c
$ ./a.out
IN STDOUT-1
IN STDOUT-3
$ cat logfile
IN LOGFILE-2
本文介绍了一个在Unix平台上重定向标准输出(STDOUT)到文件,并在之后恢复STDOUT的示例程序。通过C语言实现,该程序首先将STDOUT复制到另一个文件描述符,然后将其重定向到指定文件。完成写入后,程序会恢复STDOUT到原始状态。
798

被折叠的 条评论
为什么被折叠?



