0

In CMD documentation https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-xp/bb490982(v=technet.10) are mentioned handles from 3 to 9.
I've never seen them in real life.

Documentation reads:

These handles are defined individually by the application and are specific to each tool.

How are they used? And what for?

Are they all opened by default? Or I have to open them from script or program somehow? How do I use them with ReadFile and WriteFile?

George Sovetov
  • 4,942
  • 5
  • 36
  • 57
  • 1
    These are C runtime low I/O file descriptors (FDs), not native File handles. The C runtime's `system` and `spawn*` functions use a reserved field of the process `STARTUPINFO` to inherit inheritable FDs to a child process. CMD itself never inherits FDs into child processes since it calls `CreateProcess` directly, but the reverse works; you can inherit FDs into a CMD shell process that's created via `system` or `spawn*`. – Eryk Sun Jul 30 '18 at 22:51
  • @melpomene Did I mistype twice?! Handles, of course. – George Sovetov Jul 31 '18 at 12:11
  • @eryksun Can I simply do `_write(3, "hello", 6)` from C code and `app.exe 3>hello.txt` in CMD? – George Sovetov Jul 31 '18 at 12:15
  • 1
    No, as I said CMD will run app.exe via `CreateProcess`, not via the C runtime `system` or `spawn` functions, so CMDs FDs are not inherited. The other way works. For example, you can create a pipe FD pair via `_pipe`, write some text to it, and display it via `system("more <&%d")` (after substituting the read FD for `%d`). – Eryk Sun Jul 31 '18 at 12:28

1 Answers1

2

As your link states:

Handle    Numeric equivalent  Description
          of handle                      
========= =================== =======================================
STDIN         0               Keyboard input

STDOUT        1               Output to the Command Prompt window

STDERR        2               Error output to the Command Prompt window

UNDEFINED     3-9             These handles are defined individually
                              by the application and are specific to 
                              each tool.

A practical use in batch files is to read several source files in parallel:

See these references:
https://stackoverflow.com/a/28864990/6811411
Combining multiple text files into one
http://www.dostips.com/forum/viewtopic.php?f=3&t=3126