Write simultaneousely to two streams

前端 未结 5 2011
-上瘾入骨i
-上瘾入骨i 2020-12-11 19:06

Is there a way to to couple two streams (or file descriptors) together so that writing to one stream will also write to the second one? (C, Linux)

Thanks.

5条回答
  •  自闭症患者
    2020-12-11 19:35

    User laalto is correct, but on Linux, the function you are looking for is called fopencookie. Correcting laalto's example for Linux results in:

    int my_writefn(void *cookie, const char *data, int n) {
      FILE **files = (FILE **)cookie;
      fwrite(data, n, 1, files[0]);
      return fwrite(data, n, 1, files[1]);
    }
    
    int noop(void) { return 0; }
    cookie_io_functions_t my_fns = {
      (void*) noop,
      (void*) my_writefn,
      (void*) noop,
      (void*) noop
    };
    
    FILE *files[2] = ...;
    
    FILE *f = fopencookie((void *)files, "w", my_fns);
    
    // ... use f as you like ...
    

    When you write to f, the system will execute your my_writefn function passing it the data that was passed to fwrite. To make things easier, you may also want to change the buffering for your file stream to be line oriented:

    setvbuf(f, NULL, _IOLBF, 0);
    

    That will buffer up the data passed to fwrite until a newline is output or any data is read from any stream attached to the processes (e.g. stdin). NOTE: you must call sevbuf after fopencookie but before any data is written to the stream.

    I use line buffering because I usually use fopencookie to redirect stderr to syslog, or over a network socket, and processing line oriented data is easier and more efficient.

提交回复
热议问题