Output shows up in console, but disappears when re

2019-03-02 13:05发布

问题:

I'm using a tool that tests hard disks, fstest.exe. It runs fine from the command line, displaying how long it took to do various file-creation/-deletion/-mangling tasks. The usual output, when run from the command line as fstest.exe otherParams, looks like this:

---
CPU Usage: 0.0%
Disk reads/sec: 0
Disk writes/sec: 0
Disk bytes/read: 0
Disk bytes/write: 0
Test duration: 0 milliseconds, 1153 ticks (3507177 ticks/sec)
---

The trouble is that when I redirect the output to file, it doesn't display anything:

fstest.exe otherParams > out.txt creates an empty out.txt file, even though the command otherwise executed just fine (and created a few test-files as part of its execution).

How can I force this application to redirect output to a file? I've tried looking at it more closely with PowerShell (via Start-Process), and both the standard-out and standard-error streams are just empty.

Other things I've tried:

cmd /c "fstest.exe otherParams > out.txt"

fstest.exe otherParams 2>&1 >> out.txt

fstest.exe otherParams | sort

powershell Start-Process -FilePath .\fstest.exe -ArgumentList @("create2", "-openexisting") -RedirectStandardOutput out.txt -RedirectStandardError err.txt -wait

(That creates both out.txt and err.txt, both empty.)

What would cause an application to change its output depending on whether it's redirected, and is there any way I can make it redirect to file?

UPDATE: I've gotten my hands on the source code. It's C++, and the output is just straightforward printf statements.

回答1:

It turns out the program in question wasn't flushing stdout after doing a printf to it. Apparently, cmd is willing to flush that buffer when printing to the console, but not when redirecting output to a file. (Or perhaps the file handle is closed before the console could force a flush.) The program was exiting normally (via return, exit code always 0).

To answer the question: I had to fix the program; there was nothing I could do with command-line switches or redirects to change it.



回答2:

CMD can handle up to 10 file descriptors. Try redirecting them to separate files to identify the descriptor your program writes to:

fstest.exe {params} 0>out0.txt 3>out3.txt 4>out4.txt 5>out5.txt ...


回答3:

If it's writing to standard error, instead of standard output, redirect thusly:

fstest.exe otherParams 2> out.txt


标签: windows cmd