V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Distributions
Ubuntu
Fedora
CentOS
中文资源站
网易开源镜像站
pkookp8
V2EX  ›  Linux

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

  •  
  •   pkookp8 · 2018-04-25 14:55:47 +08:00 via Android · 2966 次点击
    这是一个创建于 2165 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

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

    12 条回复    2018-04-28 08:45:00 +08:00
    geelaw
        1
    geelaw  
       2018-04-25 15:02:00 +08:00 via iPhone   ❤️ 1
    这个问题 doesn ’ t have to be Linux specific.

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

    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
        4
    changnet  
       2018-04-25 15:54:51 +08:00 via Android
    看了很多方案,查过很多资料,然后我还是决定自己写个函数,才几百行代码,大不了重定义 printf
    q397064399
        5
    q397064399  
       2018-04-25 17:14:19 +08:00
    tee Linux 的哲学,,一个工具只干好一件事件
    pkookp8
        6
    pkookp8  
    OP
       2018-04-25 17:40:17 +08:00 via Android
    @q397064399 我猜 tee 的原理就是获取数据后同时扔给 stdout 和文件?
    pkookp8
        7
    pkookp8  
    OP
       2018-04-25 17:41:24 +08:00 via Android
    @changnet 哈哈哈,现成写文件的代码有,我司代码也是用的这个接口,就是第三方库里的 printf 不好替换
    pkookp8
        8
    pkookp8  
    OP
       2018-04-25 17:43:08 +08:00 via Android
    @jasonyang9 对,我也认为是有一个缓冲区 buffer
    q397064399
        9
    q397064399  
       2018-04-25 17:51:50 +08:00
    @pkookp8 #6 应该是的,,本来这种事情,就应该交给 tee 去做 而不是你又重新造个轮子
    tatsuteng
        10
    tatsuteng  
       2018-04-25 23:54:30 +08:00
    试了一下,用 pf=fopen 打开文件,用 setvbuf 设成 IONBF,然后在其中在 fork 一个进程里把 stdout=pf 就可以了(没有试线程,懒...)
    lolizeppelin
        11
    lolizeppelin  
       2018-04-26 09:46:06 +08:00 via Android
    文件打开的时候设置无缓冲呀
    plko345
        12
    plko345  
       2018-04-28 08:45:00 +08:00 via Android
    其实 linux 下几乎什么工具都有,而且都很优秀,只是能不能发现
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2850 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 11:42 · PVG 19:42 · LAX 04:42 · JFK 07:42
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.