【随笔记】Linux/Win 平台调用外部命令并获取执行结果

Linux:

有些命令输出结果并不是通过 ”标准输出“,而是通过 "错误输出",因此为了能获取到所有的执行结果,需要将 "错误输出" 重定向 "标准输出"。

bool runShellCommand(std::string &result, const char *cmd)
{
	FILE *fp = NULL;
	std::string command;
	char buf[128] = {0};
	
	command = cmd;
	command.append(" 2>&1"); // 错误输出重定向到标准输出
	if((fp = popen(command.c_str(), "r")) == NULL){
		return false;
	}
	
	size_t len = 0;
	result.clear();
	while(fgets(buf, sizeof(buf), fp) != NULL){
		result.append(buf);
	}
	pclose(fp);
	
    return true;
}

Windows:

BOOL runShellCommand(std::string &sResult, const char *pCommand)
{
	SECURITY_ATTRIBUTES sa;
	HANDLE hRead, hWrite;
	STARTUPINFO si;
	PROCESS_INFORMATION pi;
	std::string sCommand = "Cmd.exe /C ";

	sResult.clear();
	sCommand.append(pCommand);
	sa.nLength = sizeof(SECURITY_ATTRIBUTES);
	sa.lpSecurityDescriptor = NULL;
	sa.bInheritHandle = TRUE;
	if (!CreatePipe(&hRead, &hWrite, &sa, 0)) {
		return FALSE;
	}

	si.cb = sizeof(STARTUPINFO);
	GetStartupInfo(&si);
	si.hStdError = hWrite;            //把创建进程的标准错误输出重定向到管道输入  
	si.hStdOutput = hWrite;           //把创建进程的标准输出重定向到管道输入  
	si.wShowWindow = SW_HIDE;
	si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;

	//关键步骤,CreateProcess函数参数意义请查阅MSDN  
	if (!CreateProcess(NULL, (LPSTR)sCommand.c_str(), NULL, NULL, TRUE, NULL, NULL, NULL, &si, &pi)) {
		CloseHandle(hWrite);
		CloseHandle(hRead);
		return FALSE;
	}
	CloseHandle(hWrite);

	DWORD bytesRead = 0;
	char buff[1024] = { 0 };
	while (true)
	{
		memset(buff, 0x00, sizeof(buff));
		if (ReadFile(hRead, buff, sizeof(buff), &bytesRead, NULL)) {
			sResult.append(buff);
			continue;
		}
		break;
	}
	CloseHandle(hRead);
	CloseHandle(pi.hProcess);
	CloseHandle(pi.hThread);
	return TRUE;
}

你可能感兴趣的:(Linux,应用开发,Windows,应用开发,笔记)