سؤال

I want to write a console emulator in Windows. I need to start a cmd.exe (with SW_HIDE) from a GUI application, and then AttachConsole it.

// cmdline is a writable L"cmd"
// start_info contains a SW_HIDE
PROCESS_INFORMATION proc_info;
CreateProcess(NULL, cmdline, NULL, NULL, false, 0, NULL, NULL, &start_info, &proc_info);
AttachConsole(proc_info.dwProcessId);

But AttachConsole fails with ERROR_GEN_FAILURE (31), which indicates "the specified process does not exist" .

It seems that when CreateProcess returns, the console of cmd.exe hasn't been fully initialized, since adding a Sleep(100); before AttachConsole solves the problem.

So how can I wait until I can AttachConsole without Sleep-ing a random number?

هل كانت مفيدة؟

المحلول

Possibly you could write a helper console app that you communicate with. It can signal your main app when it starts (by which time its console will be created). The main app can tell the helper what/how to spawn the "real" child console app. If written in C with no default libraries, the helper can end up being just a few KB big, not much overhead.

نصائح أخرى

You can just loop while AttachConsole is returning ERROR_GEN_FAILURE

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top