Scene:
1. There are some external tool commands that need to be called through a program, such as starting a server or using network commands to get output.
2. Use the anonymous pipe createpipe to get the child process output.
Reference:
1. MSDN topic "Creating a child Process with redirected Input and Output".
2. Chapter of the Windows core programming process.
Code:
#include "test_shellrun.h" #include <stdlib.h> #include <stdint.h> #include <iostream> #include < Windows.h>using namespace Std;bool executecommandnowait (const wchar_t* command) {startupinfow startupinfo = {sizeof ( STARTUPINFOW)}; Getstartupinfow (&startupinfo); Startupinfo.dwflags=0;startupinfo.wshowwindow=sw_hide;bool ret = true; Process_information info;wchar_t* wlpcmd = wcsdup (command); if (CREATEPROCESSW (null, wlpcmd, NULL, NULL, TRUE, CREATE _no_window, NULL, NULL, &startupinfo, &info)) {CloseHandle (info.hprocess); CloseHandle (Info.hthread);} else{ret = false;} Free (wlpcmd); return ret;} std::string executecommandandwait (const wchar_t* command,uint32_t wait_millisecond) {security_attributes sa; HANDLE hchildstdoutrd,hchildstdoutwr;sa.nlength = sizeof (security_attributes); sa.lpsecuritydescriptor = NULL; Sa.binherithandle = true;std::string buf;if (! CreatePipe (&hchildstdoutrd,&hchildstdoutwr,&sa,0)) {return buf;} if (! Sethandleinformation (HchildstdouTRd, Handle_flag_inherit, 0)) {CloseHandle (HCHILDSTDOUTWR); CloseHandle (HCHILDSTDOUTRD); return buf;} Startupinfo si; Process_information Pi; ZeroMemory (&pi, sizeof (process_information)); ZeroMemory (&si, sizeof (STARTUPINFO)); SI.CB = sizeof (STARTUPINFO); Si.hstderror = Hchildstdoutwr;si.hstdoutput = Hchildstdoutwr;si.dwflags |= startf_usestdhandles;wchar_t* wlpcmd = Wcsdup (command);//create_unicode_environmentif (! CREATEPROCESSW (NULL, wlpcmd,null,null,true,0, Null,null,&si,&pi)) {CloseHandle (HCHILDSTDOUTWR); CloseHandle (HCHILDSTDOUTRD); CloseHandle (pi.hprocess); CloseHandle (Pi.hthread); free (wlpcmd); return buf;} WaitForSingleObject (Pi.hprocess,wait_millisecond); CloseHandle (pi.hprocess); CloseHandle (Pi.hthread); CloseHandle (HCHILDSTDOUTWR); char buffer[1024] = {0};D word bytesread; BOOL ret = False;while (true) {ret = ReadFile (hchildstdoutrd,buffer,1024,&bytesread,null); if (!ret | | bytesread = 0) { break;} Buf.append (Buffer,bytesread);} CloseHandle (HCHILDSTDOUTRD); free (wlpcmd); RetuRN buf;}
Call:
Executecommandnowait (L "notepad.exe"); std::string output = executecommandandwait (l "Ping www.baidu.com", -1); cout < < "output:" << output << Endl;
Note: When reading the output of the grandson process, the ReadFile is a child process that creates a child process that is stuck, and this problem is temporarily invoked with a thread timer:
CancelIoEx
Close ReadFile, there is no better way, who knows to leave a statement.
[Windows]_[Primary]_[Create independent sub-processes and read output of child processes]