三種方法cmd輸出重定向(推薦boost.process)

  有些場景需要通過執行cmd命令,並且獲取返回的結果。有三種方法:  

  1. boost.process
  2. windows api
  3. _popen

1.boost.process 

#include "boost/process.hpp"
#include "boost/process/windows.hpp"


std::string GetCmdResult(std::string cmd)
{
	namespace bp = boost::process;
	std::string strResult;
	std::error_code ec;
	bp::ipstream is;
	bp::system(cmd, bp::std_out > is, ec,boost::process::windows::create_no_window);
	if (!ec)
	{
		char sz[1024] = { 0 };
		is.read(sz, 1024);
		strResult = sz;
	}
	return strResult;
}

2.windows api 

	std::string GetCmdResult(std::string cmd)
	{
		std::string strResult;
		SECURITY_ATTRIBUTES saPipe;
		saPipe.nLength = sizeof(SECURITY_ATTRIBUTES);
		saPipe.lpSecurityDescriptor = NULL;
		saPipe.bInheritHandle = TRUE;

		HANDLE hReadPipe, hWritePipe;
		BOOL bSuccess = CreatePipe(&hReadPipe,
			&hWritePipe,
			&saPipe,
			0);
		if (!bSuccess)
			return "";

		PROCESS_INFORMATION pi;
		STARTUPINFOA si;
		memset(&si, 0, sizeof(si));
		GetStartupInfoA(&si);
		si.hStdError = hWritePipe;
		si.hStdOutput = hWritePipe;
		si.wShowWindow = SW_HIDE; //隱藏命令行窗口
		si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
		std::vector<char> cmdline(cmd.begin(), cmd.end());
		cmdline.push_back(0);
		if (CreateProcessA(NULL, &cmdline[0], NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi))
		{
			DWORD dwRet = WaitForSingleObject(pi.hProcess, 3*1000);
			char result[1024] = { 0 };
			DWORD dw;
			ReadFile(hReadPipe, result, 1024, &dw, NULL);
			strResult = result;
			CloseHandle(pi.hThread);
			CloseHandle(pi.hProcess);
		}

		CloseHandle(hReadPipe);
		CloseHandle(hWritePipe);
		return strResult;
	}

 

3. _popen創建一個管道,通過管道讀取cmd輸出的結果

	std::string GetCmdResult(QString cmd)
	{
		std::string strResult;
		char result[1024] = { 0 };
		auto file = _popen(strResult.c_str(), "r");
		if (nullptr != file)
		{
			while (fgets(result, 1024, file) != nullptr)
			{
				strResult += result;
			}
			_pclose(file);
		}
		return strResult;
	}

這個方法有缺陷,不能等到cmd執行完成後,獲取結果,所以有時候獲取的數據不完整。

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章