Windows C++运行命令编程
- 一、命令处理方式
- 二、_popen函数
- 三、重定向的子进程
- 四、参考链接
一、命令处理方式
Windows下编程经常需要使用批处理指令(bat或cmd),因此如何执行命令和获取返回数据是一个关键点。
- 对于控制台程序,使用_popen函数建立管道
- 对于windows应用程序(含控制台程序),使用重定向输入和输出流创建子进程
注意:_open仅适用控制台程序,不适用于UWP,且对Windows程序_popen返回的是无效文件指针
文章来源:https://uudwc.com/A/P599j
二、_popen函数
#include <stdio.h>
int main(int argc, char *argv[])
{
FILE* pPipe;
char psBuffer[128];
// 创建管道 模式 r:读 w:写 b:二进制 t:文本
if ((pPipe = _popen("dir", "rt")) == NULL)
return -1;
// 按行循环读取并输出
while (fgets(psBuffer, 128, pPipe))
puts(psBuffer);
return 0;
}
三、重定向的子进程
CreatePipe 创建匿名管道,并将句柄返回到管道的读取和写入端文章来源地址https://uudwc.com/A/P599j
#include <windows.h>
#include <stdio.h>
HANDLE g_hStd_OUT_Rd = NULL;
HANDLE g_hStd_OUT_Wr = NULL;
int main(int argc, char *argv[])
{
// 设置管道继承属性
SECURITY_ATTRIBUTES saAttr;
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
// 创建子进程标准输出,本例中父进程Read,子进程Write
if (!CreatePipe(&g_hStd_OUT_Rd, &g_hStd_OUT_Wr, &saAttr, 0))
{
printf("管道创建失败");
return -1;
}
// Read句柄不继承
SetHandleInformation(g_hStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0);
// 子进程信息
STARTUPINFO startInfo;
PROCESS_INFORMATION piProcInfo;
memset(&startInfo, 0, sizeof(STARTUPINFO));
memset(&piProcInfo, 0, sizeof(PROCESS_INFORMATION));
// 重定向输出
startInfo.cb = sizeof(STARTUPINFO);
startInfo.hStdError = g_hStd_OUT_Wr;
startInfo.hStdOutput = g_hStd_OUT_Wr;
startInfo.wShowWindow = HIDE_WINDOW;
startInfo.dwFlags |= STARTF_USESTDHANDLES;
// 第五个参数表示继承
BOOL ret = CreateProcess(NULL, "cmd /c dir", NULL, NULL, TRUE, 0, NULL, NULL, &startInfo, &piProcInfo);
if (!ret)
{
printf("进程创建失败");
return -1;
}
// 等待进程完成
WaitForSingleObject(piProcInfo.hProcess, 10000);
// 读前关闭写句柄
CloseHandle(g_hStd_OUT_Wr);
g_hStd_OUT_Wr = 0;
// 管道读取
DWORD dwRead;
char chBuf[4096] = { 0 };
while (ReadFile(g_hStd_OUT_Rd, chBuf, sizeof(chBuf), &dwRead, NULL) && (dwRead != 0))
{
puts(chBuf);
}
// 关闭句柄
CloseHandle(piProcInfo.hProcess);
CloseHandle(piProcInfo.hThread);
CloseHandle(g_hStd_OUT_Rd);
return 0;
}
四、参考链接
- _popen, _wpopen
- 使用重定向输入和输出创建子进程
- 通用 Windows 平台应用中不支持的 CRT 函数