相关疑难解决方法(0)

如何缓冲内存中的stdout并从专用线程写入

我有一个包含许多工作线程的C应用程序.至关重要的是,这些不会阻塞工作线程需要写入磁盘上的文件,我让它们写入内存中的循环缓冲区,然后有一个专用线程将该缓冲区写入磁盘.

工作线程不再阻塞.专用线程可以在写入磁盘时安全地阻塞,而不会影响工作线程(写入磁盘时它不会保持锁定).我的内存缓冲区调整得足够大,以至于编写器线程可以跟上.

一切都很好.我的问题是,我如何为stdout实现类似的东西?

我可以宏printf()写入内存缓冲区,但我无法控制可能写入stdout的所有代码(其中一些代码在第三方库中).

思考?NickB

c stdout file buffering

22
推荐指数
2
解决办法
3万
查看次数

将stdout/stderr重定向到unix c ++下的文件 - 再次

我想做的事

将stdout和stderr重定向到c ++中的一个或多个文件

为什么我需要它

我正在使用一个外部的,预编译的第三方库,它产生了大量的输出,我想将其重定向到日志文件以保持控制台清洁.

条件

兼容性不是问题,代码只能在Unix系统上运行.重定向不仅应该影响c ++风格的打印(std :: cout <<"hello world"<< std :: endl),还应该影响c风格的打印(printf("hello world \n")).

到目前为止我尝试过的

我一直在浏览stackoverflow半天,为有类似问题的人阅读多个答案.借助这些答案,我能够将以下代码组合在一起:


#include <stdio.h>
#include <iostream>
#include <fcntl.h>
#include "unistd.h"

const int stdoutfd(dup(fileno(stdout)));

int redirect_stdout(const char* fname){
  fflush(stdout);
  int newstdout = open(fname, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP |     S_IROTH);
  dup2(newstdout, fileno(stdout));
  close(newstdout);
}

int restore_stdout(){
  fflush(stdout);
  dup2(stdoutfd, fileno(stdout));
  close(stdoutfd);
  return stdoutfd;
}

int main(){
  redirect_stdout("/dev/null");
  std::cout << "invisible 1" << std::endl;
  restore_stdout();
  std::cout << "visible 1" << std::endl;
  redirect_stdout("/dev/null");
  std::cout …
Run Code Online (Sandbox Code Playgroud)

c c++ io file-descriptor io-redirection

7
推荐指数
2
解决办法
8130
查看次数

标签 统计

c ×2

buffering ×1

c++ ×1

file ×1

file-descriptor ×1

io ×1

io-redirection ×1

stdout ×1