命令提示符如何知道何时等待退出?

我试图用 c # 重新编写一个命令提示符。我想知道命令提示符如何知道何时等待进程开始退出,何时不等待被调用的进程退出。

例如,如果您键入命令提示符“ notepad”,记事本将启动,但您仍然可以执行其他命令。但是,如果您打开一个实用程序,比如 more. com、 ping.exe 或另一个实用程序,它将等待正在执行的程序完成,然后再让您执行另一个命令。

命令提示符如何知道何时等待退出,以及如何在 C # 中模拟这种行为?

4244 次浏览

If the application is a Win32 GUI application, it will just run and command prompt won't wait for it to exit.

If the application is a console application, it will run in the command prompt and you'll need to wait for it to finish to get the command prompt back.

EDIT:

OK. It seems you need technical explanation. If you want to emulate the same feature in your application, you can check IMAGE_OPTIONAL_HEADER of EXE files here.

Inside IMAGE_OPTIONAL_HEADER, there is:

 WORD                 Subsystem;

If SubSystem == 0x02 it means it's a GUI application.

If SubSystem == 0x03 it means it's a command prompt app.

EDIT 2:

If you want to see it in action:

  1. Download http://www.ntcore.com/exsuite.php

  2. Copy calc.exe or notepad.exe to your desktop

  3. Open copied calc.exe in CFF Explorer

  4. Navigate to Nt Headers -> Optional Headers

  5. Change SubSystem from 0x002 to 0x003

  6. Save it

Now run the new modified calc and you'll see the command prompt wait for it to be terminated.

When you start a new process, a GUI application in this context that actually works outside the boundaries of the prompt, the prompt will not wait. But, if you run a command that works entirely under the boundaries of the current instance of a prompt, it waits.

So, command notepad just starts the Notepad application and leaves control of application. While, command ipconfig runs under a domain (no this is not application domain), of the prompt.

To extremely generalize, when you use Process.Start in your C# equivalent, do not wait. It anyway will not.

The default from a command prompt is to spawn the GUI program in a separate process/fork. However, you can run notepad (or other GUI program) inline with your command prompt / shell script:

start /w notepad.exe

This way, the command prompt / shell script only continues after the notepad.exe process has terminated.

Hope this helps, TW