Skip to content

Instantly share code, notes, and snippets.

@ityuhui
Created September 20, 2016 08:06
Show Gist options
  • Save ityuhui/3de898a9eacde0fe5c9a1fe4b1a6edd3 to your computer and use it in GitHub Desktop.
Save ityuhui/3de898a9eacde0fe5c9a1fe4b1a6edd3 to your computer and use it in GitHub Desktop.
Windows 执行命令行程序并读取输出
static int
ExeWindowsCmd(char *result, int reslen, const char *pszCmd)
{
int rc = 0;
SECURITY_ATTRIBUTES sa = { sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
HANDLE hRead, hWrite;
if (!CreatePipe(&hRead, &hWrite, &sa, 0))
{
return -1;
}
STARTUPINFO si = { sizeof(STARTUPINFO) };
GetStartupInfo(&si);
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
si.wShowWindow = SW_HIDE;
si.hStdError = hWrite;
si.hStdOutput = hWrite;
PROCESS_INFORMATION pi;
if (!CreateProcess(NULL, pszCmd, NULL, NULL, TRUE, NULL, NULL, NULL, &si, &pi))
{
return -1;
}
CloseHandle(hWrite);
#define BUFSIZE 1024
char buff[BUFSIZE] = { 0 };
DWORD dwRead = 0;
BOOL bSuccess;
for (;;)
{
// Read from standard input and stop on error or no data.
bSuccess = ReadFile(hRead, buff, BUFSIZE, &dwRead, NULL);
strncat(result, buff, dwRead);
memset(buff, 0, sizeof(BUFSIZE));
if (!bSuccess || dwRead == 0) {
break;
}
}
result[reslen - 1] = '\0';
CloseHandle(hRead);
return rc;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment