linux单线程切换屏蔽stdout小组件


 1 #ifndef PRINT_H
 2 #define PRINT_H
 3 
 4 #include <stdio.h>
 5 class ReplaceStdout
 6 {
 7 public:
 8     ReplaceStdout();
 9     ~ReplaceStdout();
10     bool isOK() { return _ok; }
11 private:
12     bool _ok;
13 };
14 void print(const char* format, ...);
15 #endif
print.h

 

 1 #include "print.h"
 2 #include <stdarg.h>
 3 #include <algorithm>
 4 
 5 const static char* name = "/dev/null";
 6 static FILE* std_file = fopen(name, "w");
 7 
 8 bool replace()
 9 {
10     if (std_file) {
11         fflush(stdout);
12         std::swap(stdout->_fileno, std_file->_fileno);
13         return true;
14     }
15     return false;
16 }
17 
18 ReplaceStdout::ReplaceStdout():
19     _ok(replace())
20 {
21 }
22 
23 ReplaceStdout::~ReplaceStdout()
24 {
25     replace();
26 }
27 
28 void print(const char* format, ...)
29 {
30     va_list args;
31     va_start(args, format);
32     vfprintf(1 == stdout->_fileno ? stdout : std_file,
33             format, args);
34     va_end(args);
35 }
print.cpp

 

 1 #include "print.h"
 2 
 3 int main(int argc, char* argv[])
 4 {
 5     ReplaceStdout replace;
 6     printf("printf hello\n");
 7     print("print hello\n");
 8     //{ ReplaceStdout replace; }
 9     ReplaceStdout recover;
10     printf("printf world\n");
11     print("print world\n");
12     return 0;
13 }
main

 



转载于:https://www.cnblogs.com/-chaos/p/3335836.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值