开发者

How do I detect when output is being redirected?

I have a Win32 application written in C that can have its console output via printf() redirected to a log file.

It would be n开发者_如何学运维ice if I could have my app. detect if it had been started with or without a redirect '>'.

Any ideas?


Tom, thanks for the input.

I did some experiments and found this works for me..

fpost_t pos ;

fgetpos (stdout, & pos) ;

When an application's output is being redirected to a file, fgetpos() sets 'pos' to zero. It makes sense since its freshly opened stderr for you. EDIT: Actually, the value returned may be a positive integer if text has already been redirected to the log/file. So in your code you'd have something like "if (pos >= 0) bfRedirected = TRUE ;"

When an application's output is not being redirected - it's going to the console device - not a file, so fgetpos() will set 'pos' to -1.


I think that pipes are blind by nature, so you don't have a built-in way to tell whether you're being redirected. Moreover, trying to find out what's happening behind an abstraction layer is a bad habit.

If you really need to control your output, add the log file name as a command line parameter!

That being said, you can make some smart guesswork to find out:

  • A program can query the shell command history to find out the most recent commands executed.
  • If you know the path to the logfiles, you can scan that directory and see if a file has been created or changed its size.
  • Benchmark writing speed when redirected and not redirected. This would work only if your system is ultra-stable, and environment condition won't change.


There may be a way to do this - a quick google yielded this hit that might give you the hint in the right direction.


Method from Microsoft: WriteConsole fails if it is used with a standard handle that is redirected to a file. If an application processes multilingual output that can be redirected, determine whether the output handle is a console handle (one method is to call the GetConsoleMode function and check whether it succeeds).


AFAIK the answer to this is that you can't. Output redirection works by simply reading the stream of output from a given program and redirecting it to another pipe / stream. The design of file / streams is such that the writer is ignorant of the reader to the point that you shouldn't know you are being read.

Even detecting that there was a reader would be of no use because there is one in the normal case. The console is reading the output of your program and displaying it to the screen already.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜