How to run exe with output via cmd like Linux

Solution 1:

Then the program looks like running in another thread, the different thread from cmd.

Well, the program is running in a separate process, which has its own threads.

On Windows, there are two main types of programs: console and windowed.

Console programs are typically text-mode applications that print text. These already behave the way you want: you run the program, the shell (cmd.exe) waits for it finish before returning you to an interactive prompt. If the program is long-running, forcibly terminating cmd.exe will terminate the program.

Windowed programs are typically applications that have a graphical user interface (e.g. notepad.exe, explorer.exe, firefox.exe). They don't behave the way you want: when you run them through cmd.exe, cmd.exe does not wait for them and returns you to an interactive prompt immediately. The executed program runs independently of cmd.exe, and terminating one has no effect on the other.

Note that console programs can have windows and that windowed programs can have console output. So what makes a program "console" or "windowed"?

Part of the .exe specifies whether it should be run with the "console" subsystem or with the "windows" subsystem. This is configured (often implicitly) when the program was built. This can be changed after the program was built; editbin.exe (included with Visual Studio) can modify the .exe file and change which subsystem the program should use.

If you just want to see stdout and stderr output, you don't need to modify the .exe file. Normally windowed applications don't send that output anywhere, but you can change that with pipes/redirects. For example, you can run:

SomeWindowedApplication.exe > output.txt

or, if you have cat (or an equivalent) available:

SomeWindowedApplication.exe | cat

Doing so also will cause cmd.exe to wait for the program to terminate before returning you to the interactive prompt. Note that this does not have the termination behavior you want (i.e., terminating cmd.exe in the last example will terminate cat.exe, not ShowWindowedApplication.exe).

Also see:

  • https://stackoverflow.com/a/2424210/179715
  • https://stackoverflow.com/a/2628025/179715