Detect if stdout is redirected to a pipe (not to a file, character device, terminal, or socket)?

后端 未结 5 896
粉色の甜心
粉色の甜心 2021-02-14 20:50

Ideally, this would be scriptable in shell, but Perl or Python would be fine. C code could be helpful, but probably fails cost/benefit.

I recognize that redirection to a

5条回答
  •  太阳男子
    2021-02-14 21:40

    You could do an fstat to the file descriptor and check returning structure, for example, st_mode = 0x1000 (S_IFIFO) indicates a Named Pipe.

    Example with Python:

    from __future__ import print_function
    import sys
    import os
    
    print(os.fstat(sys.stdout.fileno()), file=sys.stderr)
    

    Output on windows:

    C:> python test_fd.py | more
    nt.stat_result(st_mode=4096, st_ino=0L, st_dev=0, st_nlink=0, st_uid=0, st_gid=0, st_size=0L, st_atime=0L, st_mtime=0L, st_ctime=0L)
    
    C:> python test_fd.py > test_fd.txt
    nt.stat_result(st_mode=33206, st_ino=16888498602769633L, st_dev=0, st_nlink=1, st_uid=0, st_gid=0, st_size=0L, st_atime= 1401119520L, st_mtime=1401119520L, st_ctime=1401119349L)
    

提交回复
热议问题