0

File content will be messed up if stdout and stderr are full-buffered and redirected to the same file by the shell.

Are there ways to check whether the underlying files/pipes/terminals of file pointers/descriptors/handles are the same in C++ and Python?

Buffering should be disabled only if stdout and stderr are redirected to the same file.

EDIT:
Thanks for isedev's comment.

That idea also works in Python 3.4.

def same_file(file1, file2):
    stat1, stat2 = os.fstat(file1.fileno()), os.fstat(file2.fileno())
    return (stat1.st_dev == stat2.st_dev) and (stat1.st_ino == stat2.st_ino)

This doesn't work for pipe/terminal of course.

Similar way to check for the same file in WinAPI.

Community
  • 1
  • 1
pat
  • 48
  • 9
  • 1
    this should help: http://stackoverflow.com/questions/12502552/can-i-check-if-two-file-or-file-descriptor-numbers-refer-to-the-same-file – isedev Mar 31 '16 at 00:10

1 Answers1

2

There's no standard way to determine what an FD actually refers to. It's also possible to have multiple FDs refer to the same file, which is what happens when the dup(2) family of functions are used.

Also see Getting Filename from file descriptor in C

Community
  • 1
  • 1
Mark Nunberg
  • 3,551
  • 15
  • 18