我正在尝试从运行cmd.exe命令获取unicode输出。我看到/ U开关仅适用于dir等内置命令,不适用于ipconfig等其他命令。
如果我将计算机的名称更改为中文/俄语/日语,并运行ipconfig / all,它将在控制台中正常显示。但是当我使用CreateProcesssW()并将输出重定向到管道时,即使在控制台上正确显示了unicode,也无法返回unicode。
#include <Windows.h>
#include <stdio.h>
int main() {
HANDLE hPipeRead, hPipeWrite;
SECURITY_ATTRIBUTES saAttr = { sizeof(SECURITY_ATTRIBUTES) };
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
if (!CreatePipe(&hPipeRead, &hPipeWrite, &saAttr, 0))
return 0;
STARTUPINFO si = { sizeof(STARTUPINFO) };
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
si.hStdOutput = hPipeWrite;
si.hStdError = hPipeWrite;
si.wShowWindow = SW_HIDE;
PROCESS_INFORMATION pi = { 0 };
WCHAR works[] = L"C:\\windows\\system32\\cmd.exe /u /c dir C:\\test";
WCHAR dont[] = L"cmd.exe /u /c ipconfig";
BOOL fSuccess = CreateProcessW(NULL, works, NULL, NULL, TRUE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi);
if (!fSuccess) {
CloseHandle(hPipeWrite);
CloseHandle(hPipeRead);
return 0;
}
BOOL bProcessEnded = FALSE;
for (; !bProcessEnded;) {
bProcessEnded = WaitForSingleObject(pi.hProcess, 50) == WAIT_OBJECT_0;
while (TRUE) {
CHAR *buf = NULL;
DWORD dwRead = 0;
DWORD dwAvail = 0;
if (!PeekNamedPipe(hPipeRead, NULL, 0, NULL, &dwAvail, NULL))
break;
if (!dwAvail)
break;
buf = HeapAlloc(GetProcessHeap(), 0, dwAvail);
if (buf == NULL) {
return 0;
}
if (!ReadFile(hPipeRead, buf, dwAvail, &dwRead, NULL) || !dwRead)
break;
printf("%ls", buf);
}
}
CloseHandle(hPipeWrite);
CloseHandle(hPipeRead);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
Sleep(10000);
return 0;
}
我试图弄清楚如何从cmd.exe中运行的所有内容中获取unicode。