我正在尝试将 stdin 重定向到我选择的文件,在 C 程序(win32 API)内留下重定向 stderr 或 stdout 的可能性。
我正在编写一个我在 cygwin 上运行的 shell,期望的效果是让 cat < file 工作。
到目前为止,这是我的代码:
static HANDLE createinputHandle(PCSTR filename, SECURITY_ATTRIBUTES sa)
{
return CreateFile(
filename,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
}
static VOID RedirectHandle(STARTUPINFO *psi, HANDLE hFile, INT opt)
{
if (hFile == INVALID_HANDLE_VALUE)
return;
psi->dwFlags |= STARTF_USESTDHANDLES;
switch (opt) {
case STD_INPUT_HANDLE:
psi->hStdInput = GetStdHandle(STD_INPUT_HANDLE);
psi->hStdInput = hFile;
break;
case STD_OUTPUT_HANDLE:
psi->hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
psi->hStdOutput = hFile;
break;
case STD_ERROR_HANDLE:
psi->hStdError = GetStdHandle(STD_ERROR_HANDLE);
psi->hStdError = hFile;
break;
}
command_func() {
STARTUPINFO si;
PROCESS_INFORMATION pi;
bool result;
DWORD wait_result;
HANDLE inHandle, outHandle, errHandle;
SECURITY_ATTRIBUTES sa;
ZeroMemory(&si, sizeof(si)); //macro to init with zero's
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
ZeroMemory(&sa, sizeof(sa));
sa.bInheritHandle = TRUE;
inHandle = INVALID_HANDLE_VALUE;
outHandle = INVALID_HANDLE_VALUE;
errHandle = INVALID_HANDLE_VALUE;
if(inputFile != NULL) {
inHandle = createinputHandle(inputFile, sa);
SetHandleInformation(inHandle, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);
//added
RedirectHandle(&si, inHandle, STD_INPUT_HANDLE);
}
result = CreateProcess(
NULL,
cmd, /*if you want to test this, you need to change cmd to something like "ls -l" */
NULL,
NULL,
TRUE,
0,
NULL,
NULL,
&si,
&pi);
}
这个标准输入重定向不起作用,我做错了什么?
谢谢 !