如何缓冲内存中的stdout并从专用线程中写入 [英] How to buffer stdout in memory and write it from a dedicated thread

查看:146
本文介绍了如何缓冲内存中的stdout并从专用线程中写入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C应用程序有很多工作线程。重要的是,这些不阻止工作线程需要写入磁盘上的文件的位置,我们将它们写入内存中的循环缓冲区,然后有一个专用线程将该缓冲区写入磁盘。



工作线程不再阻塞。专用线程可以在写入磁盘时安全地阻止,而不会影响到工作线程(在写入磁盘时不会保留锁定)。我的内存缓冲区被调整到足够大,写程序线程可以跟上。



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



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



想法?
NickB

解决方案

我喜欢使用 freopen 。您也可以使用 stdout 重定向到管道rel = noreferrer> dup dup2 ,然后使用读取以从管道中获取数据。



如下所示:

  #include< stdio.h> 
#include< stdlib.h>
#include< unistd.h>

#define MAX_LEN 40

int main(int argc,char * argv []){
char buffer [MAX_LEN + 1] = {0};
int out_pipe [2];
int saved_stdout;

saved_stdout = dup(STDOUT_FILENO); / *保存stdout以便显示* /

if(pipe(out_pipe)!= 0){/ * make a pipe * /
exit(1);
}

dup2(out_pipe [1],STDOUT_FILENO); / *将stdout重定向到管道* /
close(out_pipe [1]);

/ *发送到printf的任何内容现在应该在管道下面* /
printf(ceci n'est pas une pipe);
fflush(stdout);

read(out_pipe [0],buffer,MAX_LEN); / *从管道读入缓冲区* /

dup2(saved_stdout,STDOUT_FILENO); / *重新连接stdout进行测试* /
printf(read:%s\\\
,buffer);

return 0;
}


I have a C application with many worker threads. It is essential that these do not block so where the worker threads need to write to a file on disk, I have them write to a circular buffer in memory, and then have a dedicated thread for writing that buffer to disk.

The worker threads do not block any more. The dedicated thread can safely block while writing to disk without affecting the worker threads (it does not hold a lock while writing to disk). My memory buffer is tuned to be sufficiently large that the writer thread can keep up.

This all works great. My question is, how do I implement something similar for stdout?

I could macro printf() to write into a memory buffer, but I don't have control over all the code that might write to stdout (some of it is in third-party libraries).

Thoughts? NickB

解决方案

I like the idea of using freopen. You might also be able to redirect stdout to a pipe using dup and dup2, and then use read to grab data from the pipe.

Something like so:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define MAX_LEN 40

int main( int argc, char *argv[] ) {
  char buffer[MAX_LEN+1] = {0};
  int out_pipe[2];
  int saved_stdout;

  saved_stdout = dup(STDOUT_FILENO);  /* save stdout for display later */

  if( pipe(out_pipe) != 0 ) {          /* make a pipe */
    exit(1);
  }

  dup2(out_pipe[1], STDOUT_FILENO);   /* redirect stdout to the pipe */
  close(out_pipe[1]);

  /* anything sent to printf should now go down the pipe */
  printf("ceci n'est pas une pipe");
  fflush(stdout);

  read(out_pipe[0], buffer, MAX_LEN); /* read from pipe into buffer */

  dup2(saved_stdout, STDOUT_FILENO);  /* reconnect stdout for testing */
  printf("read: %s\n", buffer);

  return 0;
}

这篇关于如何缓冲内存中的stdout并从专用线程中写入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆