Go to the documentation of this file.00001 #include "../interface/CloseCoutSentry.h"
00002
00003 #include <cstdio>
00004 #include <unistd.h>
00005
00006 bool CloseCoutSentry::open_ = true;
00007 int CloseCoutSentry::fdOut_ = 0;
00008 int CloseCoutSentry::fdErr_ = 0;
00009 FILE * CloseCoutSentry::trueStdOut_ = 0;
00010
00011 CloseCoutSentry::CloseCoutSentry(bool silent) :
00012 silent_(silent), stdOutIsMine_(false)
00013 {
00014 if (silent_) {
00015 if (open_) {
00016 open_ = false;
00017 if (fdOut_ == 0 && fdErr_ == 0) {
00018 fdOut_ = dup(1);
00019 fdErr_ = dup(2);
00020 }
00021 freopen("/dev/null", "w", stdout);
00022 freopen("/dev/null", "w", stderr);
00023 } else {
00024 silent_ = false;
00025 }
00026 }
00027 }
00028
00029 CloseCoutSentry::~CloseCoutSentry()
00030 {
00031 clear();
00032 }
00033
00034 void CloseCoutSentry::clear()
00035 {
00036 if (stdOutIsMine_) { fclose(trueStdOut_); trueStdOut_ = 0; }
00037 if (silent_) {
00038 reallyClear();
00039 silent_ = false;
00040 }
00041 }
00042
00043 void CloseCoutSentry::reallyClear()
00044 {
00045 if (fdOut_ != fdErr_) {
00046 char buf[50];
00047 sprintf(buf, "/dev/fd/%d", fdOut_); freopen(buf, "w", stdout);
00048 sprintf(buf, "/dev/fd/%d", fdErr_); freopen(buf, "w", stderr);
00049 open_ = true;
00050 fdOut_ = fdErr_ = 0;
00051 }
00052 }
00053
00054 void CloseCoutSentry::breakFree()
00055 {
00056 reallyClear();
00057 }
00058
00059 FILE *CloseCoutSentry::trueStdOut()
00060 {
00061 if (open_) return stdout;
00062 if (trueStdOut_) return trueStdOut_;
00063 stdOutIsMine_ = true;
00064 char buf[50];
00065 sprintf(buf, "/dev/fd/%d", fdOut_); trueStdOut_ = fopen(buf, "w");
00066 return trueStdOut_;
00067 }