Win7 VC6
1、
子进程 代码:
1 #include <windows.h> 2 #include <stdio.h> 3 4 int main() 5 { 6 Sleep(1000); 7 8 printf("Sub01 : *stdin : %x ", *stdin); 9 printf("Sub01 : *stdout : %x ", *stdout); 10 printf("Sub01 : *stderr : %x ", *stderr); 11 printf(" "); 12 13 printf("Sub01 : stdin : %x ", stdin); 14 printf("Sub01 : stdout : %x ", stdout); 15 printf("Sub01 : stderr : %x ", stderr); 16 printf(" "); 17 18 printf("Sub01 : GetStdHandle(STD_INPUT_HANDLE) return : %x ", GetStdHandle(STD_INPUT_HANDLE)); 19 printf("Sub01 : GetStdHandle(STD_OUTPUT_HANDLE) return : %x ", GetStdHandle(STD_OUTPUT_HANDLE)); 20 printf("Sub01 : GetStdHandle(STD_ERROR_HANDLE) return : %x ", GetStdHandle(STD_ERROR_HANDLE)); 21 printf(" "); 22 23 24 return 0; 25 }
2、
父进程 代码:
1 #include <windows.h> 2 #include <stdio.h> 3 4 #include <io.h> 5 #include <Fcntl.h> 6 7 int main() 8 { 9 // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** 10 // 创建 管道 11 12 HANDLE hRead = 0, hWrite = 0; 13 14 SECURITY_ATTRIBUTES sa = {0}; 15 sa.nLength = sizeof(SECURITY_ATTRIBUTES); 16 sa.lpSecurityDescriptor = NULL; 17 sa.bInheritHandle = true; 18 if (! CreatePipe(&hRead, &hWrite, &sa, 0)) 19 {return 0;} 20 printf("Parent 01 - hWrite : %x, &hWrite : %x ", hWrite, &hWrite); 21 22 // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** 23 // 创建 子进程 24 25 STARTUPINFO si = {0}; 26 si.cb = sizeof(STARTUPINFO); 27 GetStartupInfo(&si); 28 si.wShowWindow = SW_SHOW; 29 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; 30 si.hStdOutput = hWrite; 31 printf("Parent 01 - &si.hStdOutput : %x ", &si.hStdOutput); 32 33 PROCESS_INFORMATION pi = {0}; 34 if (! CreateProcess(NULL, "Console_Sub_VC6_01.exe", NULL, NULL, true, 0, NULL, NULL, &si, &pi)) 35 { 36 return 0; 37 } 38 CloseHandle(hWrite); // ZC: 这里不关闭的话,就少关闭了1次,当子进程退出时 下面的ReadFile还会继续等待数据。 39 40 // *** *** *** 41 // 接收 子进程 的标准输出 42 43 while (true) 44 { 45 printf("1 "); 46 fflush(stdout); 47 48 DWORD bytesRead = 0; 49 char cBuffer[4096] = {0}; 50 //Sleep(2000); 51 if (! ReadFile(hRead, &cBuffer[0], 4095, &bytesRead, NULL)) 52 {break;} 53 cBuffer[bytesRead] = '