How can NT character-mode application determine if its console has been inherited from parent process, as opposed to newly allocated console within CreateProcess?
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.]
you may try GetConsoleProcessList
, the first process will be the one that asks, the second is the parent, but if it has quit (for example start.exe
) then the list chain breaks and it will contain only the currently running process.
although when i check the process with Sysinternals Process Explorer, it shows ConEmuHk64.dll
in Threads tab. when i normally run my app that function reports ConEmuC64.exe <= Far.exe <= ConEmuC64.exe
processes (without the first one), or either cmd.exe
or powershell.exe
when running from the standard windows terminal.
so actually the parent process may quit but the console stays inherited
© 2022 - 2024 — McMap. All rights reserved.