1. 程式人生 > >解決system()函式執行命令彈出dos視窗問題

解決system()函式執行命令彈出dos視窗問題

問題描述:使用system()函式執行命令"net start nginx",啟動一個windows服務,會彈出一個dos視窗。同時,啟動服務的過程比較久,因此不能單純的採用WinExec()等方式呼叫,因為WinExec()呼叫方式是即呼叫即返回,還沒等命令執行完成就結束了。

       因此,這裡採用的是ShellExecute加上同步的方式。

解決思路:採用ShellExecute執行命令,同時使用同步,等待該命令執行完成。

        SHELLEXECUTEINFO ShExecInfo = {0};
	ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
	ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
	ShExecInfo.hwnd = NULL;
	ShExecInfo.lpVerb = NULL;
	ShExecInfo.lpFile = L"cmd.exe";//呼叫的程式名
	ShExecInfo.lpParameters = L"cmd.exe /c net start nginx";//呼叫程式的命令列引數
	ShExecInfo.lpDirectory = NULL;
	ShExecInfo.nShow = SW_HIDE;//視窗狀態為隱藏
	ShExecInfo.hInstApp = NULL;
	ShellExecuteEx(&ShExecInfo);
	WaitForSingleObject(ShExecInfo.hProcess,INFINITE);////等到該程序結束