Sample program: / * name: 3745739.c Copyright: idler fang author: idler fang Date: 22-01-05 22:56 Description: sample of child Process I / o redirect. * /
#include
#include
#define buffsize 4096
INT Main (int Argc, char * argv []) {const char * lpszcmd = "test.exe"; / * The following is the parameter required to create anonymous pipe * / handle hreadpipe, / * read pipe * / hwritepipe; / * write pipeline * / SECURITY_ATTRIBUTES sec_attr; / * security attributes * / / * the following parameters for creating child processes needed * / STARTUPINFO start_info; PROCESS_INFORMATION proc_info; char buff [BUFFSIZE]; / * buffer * / DWORD bytesRead; const int interval = 100; / * Update interval * / / * Create anonymous pipe * / sec_attr.binherithandle = true; / * Ensure that the pipe can be subjected to sub-process inheritance * / sec_attributes; sec_attr.lpsecurityDescriptor = null; / * Using the system Default security descriptor * / if (createpipe (& Hreadpipe, & hwritepipe, & sec_attr, 0) == 0) {FPRINTF (stderr, "anonymous pack code failed! / N"); return -1;} / * Create sub-process * / start_info.cb = sizeof (STARTUPINFO); GetStartupInfo (& start_info); start_info.hStdOutput = hWritePipe; / * redirect stdout * / start_info.hStdError = hWritePipe; / * redirect stderr * / start_info.wShowWindow = SW_HIDE; / * course No window * / s tart_info.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; / * make the above parameters take effect * / if (CreateProcess (NULL, TEXT (lpszCmd), NULL, NULL, TRUE, NULL, NULL, NULL, & start_info, & proc_info) == 0) {fprintf ( Stderr, "Child Process Creation Failed! / N"); return -1;} closehandle (hwritepipe); / * The current process does not need this write * / / * read * / for * / for (;;) { IF (Hreadpipe, Buff, Buffsize - 1, & BYTESREAD, NUFF) == NULL) Break; Printf ("% s", buff); SLEEP (Interval);} system ("pause); return 0;}
Test.c # incrude
#include Return 0;}