您有子程序的来源吗?检查它如何读取其输入(或在此处发布源代码)。
您的子程序是否使用 cmd 输入重定向,例如如果你这样做echo yes | childprogram.exe?
如果不是,则程序可能使用低级别的console functions 进行输入(可能是间接的,例如通过_getch())。在这种情况下,您可能必须使用WriteConsoleInput 来模拟输入。
或者,您的重定向代码可能有错误。在此处发布。
编辑使用 WriteConsoleInput 的示例:
#include <windows.h>
#include <process.h>
#include <stdlib.h>
#include <stdio.h>
static const INPUT_RECORD SimulatedInput [] =
{
{KEY_EVENT, {TRUE, 1, 0, 0, {L'e'}, 0}},
{KEY_EVENT, {TRUE, 1, 0, 0, {L'c'}, 0}},
{KEY_EVENT, {TRUE, 1, 0, 0, {L'h'}, 0}},
{KEY_EVENT, {TRUE, 1, 0, 0, {L'o'}, 0}},
{KEY_EVENT, {TRUE, 1, 0, 0, {L' '}, 0}},
{KEY_EVENT, {TRUE, 1, 0, 0, {L'T'}, 0}},
{KEY_EVENT, {TRUE, 1, 0, 0, {L'E'}, 0}},
{KEY_EVENT, {TRUE, 1, 0, 0, {L'S'}, 0}},
{KEY_EVENT, {TRUE, 1, 0, 0, {L'T'}, 0}},
{KEY_EVENT, {TRUE, 1, VK_RETURN, 0, {L'\r'}, 0}},
};
int main( int, char*[] )
{
printf("\n(type 'exit' to exit the subshell)\n");
// start a command interpreter asynchronously
intptr_t process_handle = _spawnlp(_P_NOWAIT, "cmd", "/k", "prompt", "SUBSHELL: ", NULL);
// get own console handle
HANDLE con_input_handle = GetStdHandle(STD_INPUT_HANDLE);
// send input to the console
DWORD n_written;
WriteConsoleInputW(con_input_handle, SimulatedInput, _countof(SimulatedInput), &n_written);
// wait for child process to exit
_cwait(NULL, process_handle, 0);
return 0;
}
上面的示例必须编译为控制台程序,因为它使用GetStdHandle 来获取控制台输入句柄。当父级是控制台应用程序时,子级控制台应用程序将与父级共享控制台。如果 parent 是 GUI 应用程序因此没有控制台,请在调用 GetStdHandle 之前使用 AttachConsole 函数附加到子进程控制台,然后在完成后调用 FreeConsole。