Do i own my console or i inherited it from my pare

2019-06-05 11:58发布

How can NT character-mode application determine if its console has been inherited from parent process, as opposed to newly allocated console within CreateProcess?

wow, so unpopular tags! adding windows to attract appropriate programmers


@anonymous downvoter: i can do limited expansion of this question based on some feedback only. State what is not clear (familiarity with Windows kernel and subsystems is required, however). Remember, lot of us here are programmers, so our humour is very specific, do not judge title pun too harsh.

1条回答
时光不老,我们不散
2楼-- · 2019-06-05 12:29

Some ideas that may or may not help - this isn't really an answer, but it's too long to fit into the comments.*

You can use GetConsoleWindow() to determine the HWND of your console. Could then see if anyone else is sharing that. Try calling GetWindowThreadProcessId on it - on some versions of windows, if I recall correctly, it seems this returns the PID of the CSRSS process - which isn't helpful. But it seems that on Win7, it returns the PID of the process that initially owns that window.

For example, I started a CMD window, and typed in more; so we have cmd.exe and more.exe sharing the same window. Spy++ reports that the HWND belongs to cmd.exe.

But use "start more" so create a new console with more in it, and spy++ reports that the new window belongs to more.exe.

This may be new behavior in Win7 (or at least may not be consistent in previous versions), however; console windows are actually owned by a helper process, conhost.exe in Win7 and csrss in previous versions. It's possible that GetWindowThreadProcessId will return the PID of those helper processes on previous versions. And who knows what it will return in a future version of Windows - console windows are "special".

--

A different approach that doesn't rely on GetWindowThreadProcessID is to:

  • determine your parent's process ID (check stackoverflow for past answers to this question!)
  • AttachConsole(pid), GetConsoleWindow(), and FreeConsole() to "peek" at what console HWND your parent process is using (if any).
  • The catch with this is that a process can be attached to only one console at a time - so you'd have to do this "peek" in a separate helper process (!) - otherwise you'd have to let go of your own console first.

Long story short, it might be possible to approximate this, but not clear that you'd actually want to do it "in real life"; the "pause if no parameters" is likely the best way to go.

[*This answer is provided for entertainment purposes only, void where prohibited, etc.]

查看更多
登录 后发表回答