應(yīng)同事需要做一個局域網(wǎng)時間同步的,找了下資料發(fā)現(xiàn)net time最方便,于新建了一個控制臺項目,用CreateProcess運行cmd命令
運行了后發(fā)現(xiàn)時間根本就沒有改變,折騰了一個晚上才發(fā)現(xiàn)錯在字符轉(zhuǎn)義上,下面的代碼是錯誤示范
//定義一個用于產(chǎn)生子進(jìn)程的STARTUPINFO結(jié)構(gòu)體 (定義見CreateProcess,函數(shù)說明)
STARTUPINFO siStartInfo;
//定義一個用于產(chǎn)生子進(jìn)程的PROCESS_INFORMATION結(jié)構(gòu)體 (定義見CreateProcess,函數(shù)說明)
PROCESS_INFORMATION piProcInfo;
//對STARTUPINFO結(jié)構(gòu)體賦值,對stdin,stdout的Handle設(shè)置為剛才得到的管道HANDLE
ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
siStartInfo.cb = sizeof(STARTUPINFO);
siStartInfo.dwFlags = STARTF_USESHOWWINDOW|STARTF_USESTDHANDLES; //允許設(shè)置showwindow和設(shè)置新進(jìn)程的輸入輸出句柄參數(shù)
siStartInfo.wShowWindow = SW_HIDE;
siStartInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); //意思是:子進(jìn)程的stdout輸出到hStdOutWrite
siStartInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE); //意思是:子進(jìn)程的stderr輸出到hStdErrWrite
siStartInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
TCHAR CommandLine[] = _T("/c net time \\192.168.1.1 /set /y >C:\\2.txt"); //
//ShellExecute(NULL, _T("open"), _T("C:\\Windows\\System32\\cmd.exe"), CommandLine, NULL, SW_SHOW);
// 產(chǎn)生子進(jìn)程,具體參數(shù)說明見CreateProcess函數(shù)
BOOL bSuccess = CreateProcess(L"C:\\Windows\\System32\\cmd.exe",
CommandLine, // 子進(jìn)程的命令行
NULL, // process security attributes
NULL, // primary thread security attributes
FALSE, // handles are inherited
CREATE_NO_WINDOW, // creation flags 如果想新進(jìn)程顯示窗口, 可以設(shè)置CREATE_NEW_CONSOLE
NULL, // use parent's environment
NULL, // use parent's current directory
&siStartInfo, // STARTUPINFO pointer
&piProcInfo); // receives PROCESS_INFORMATION
if (bSuccess)
{
TCHAR prints[MAX_PATH] = { 0 };
_stprintf_s(prints, MAX_PATH, _T("ID:%d,Process:%d\n"), piProcInfo.dwProcessId, piProcInfo.hProcess);
//MessageBox(NULL, prints, NULL, MB_SETFOREGROUND);
CloseHandle(piProcInfo.hProcess);
CloseHandle(piProcInfo.hThread);
//WaitForSingleObject(piProcInfo.hProcess, INFINITE);
}
以下是正確的代碼,寫了這么久的代碼竟然忽略了在C++兩個\\表示一個\ ,
因為遠(yuǎn)程IP是用雙\\表示的,在C++就要多加兩個\\
結(jié)束語:
感覺CreateProcess不用設(shè)置控制臺的輸入輸出流,也能執(zhí)行成功,因為時間關(guān)系就不測試了,有興趣的自己測試去.
|