Distributions
› Ubuntu
› Fedora
› CentOS
中文资源站
› 网易开源镜像站
pkookp8
V2EX  ›  Linux

问两个 Linux 下输出重定向的问题

  •  
  •   pkookp8 · Apr 25, 2018 via Android · 3960 views
    This topic created in 3115 days ago, the information mentioned may be changed or developed.

    因为用到别人的库,没有源码,printf 很多又需要收集作为定位信息发给别人,遇到了两个问题 1. c 语言不修改 printf 这个函数,有没有办法做到 printf 既输出到 stdout,也输出到某个文件 我能想到的就是 dup2(fd, 1)之后,起一个线程把 fd 中新的内容扔到 stdout 中 不行的话只能 a.out >> a.log 了

    dup2(fd, 1)之后,printf 了一个很少的信息+换行符也不能实时输出到 fd,不知道是不是因为缓冲区的原因 除了关闭 fd,有没有办法立即输出 试了 sync 没用

    12 replies  •  2018-04-28 08:45:00 +08:00
    geelaw
    geelaw
    Apr 25, 2018 via iPhone❤️1
    1
    这个问题 doesn ’ t have to be Linux specific.

    我不是 Linux 专家,不过简单的思路有 2。
    对于取消缓冲,你可以用标准 C 的方式:输出完了之后立刻 fflush。
    对于同时输出到两个出口,用 tee,它把标准输入复制到标准输出和一个指定的文件。
    kamen
    kamen
    Apr 25, 2018
    2
    command | tee commad.log
    jasonyang9
    jasonyang9
    Apr 25, 2018
    3
    关于不能实时输出到文件描述符,可能和这段说的有关系:

    Normally - Unix and Linux systems apply some intelligence to handling standard output. It's assumed that if you are sending results to a terminal, you want the output as soon as it becomes available. However, if you are sending the output to a file, then it's assumed you want better performance, so it buffers the output until the buffer is full, and then the contents of the buffer is written to the file.
    changnet
    changnet
    Apr 25, 2018 via Android
    4
    看了很多方案,查过很多资料,然后我还是决定自己写个函数,才几百行代码,大不了重定义 printf
    q397064399
    q397064399
    Apr 25, 2018
    5
    tee Linux 的哲学,,一个工具只干好一件事件
    pkookp8
    pkookp8
    OP
    Apr 25, 2018 via Android
    6
    @q397064399 我猜 tee 的原理就是获取数据后同时扔给 stdout 和文件?
    pkookp8
    pkookp8
    OP
    Apr 25, 2018 via Android
    7
    @changnet 哈哈哈,现成写文件的代码有,我司代码也是用的这个接口,就是第三方库里的 printf 不好替换
    pkookp8
    pkookp8
    OP
    Apr 25, 2018 via Android
    8
    @jasonyang9 对,我也认为是有一个缓冲区 buffer
    q397064399
    q397064399
    Apr 25, 2018
    9
    @pkookp8 #6 应该是的,,本来这种事情,就应该交给 tee 去做 而不是你又重新造个轮子
    tatsuteng
    tatsuteng
    Apr 25, 2018
    10
    试了一下,用 pf=fopen 打开文件,用 setvbuf 设成 IONBF,然后在其中在 fork 一个进程里把 stdout=pf 就可以了(没有试线程,懒...)
    lolizeppelin
    lolizeppelin
    Apr 26, 2018 via Android
    11
    文件打开的时候设置无缓冲呀
    plko345
    plko345
    Apr 28, 2018 via Android
    12
    其实 linux 下几乎什么工具都有,而且都很优秀,只是能不能发现
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2856 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 59ms · UTC 10:54 · PVG 18:54 · LAX 02:54 · JFK 05:54
    ♥ Do have faith in what you're doing.