您目前已離線,請等候您的網際網路重新連線

如何繁衍主控台處理程序,以重新導向標準控點

重要:本文是以 Microsoft 機器翻譯軟體翻譯而成,而非使用人工翻譯而成。Microsoft 同時提供使用者人工翻譯及機器翻譯兩個版本的文章,讓使用者可以依其使用語言使用知識庫中的所有文章。但是,機器翻譯的文章可能不盡完美。這些文章中也可能出現拼字、語意或文法上的錯誤,就像外國人在使用本國語言時可能發生的錯誤。Microsoft 不為內容的翻譯錯誤或客戶對該內容的使用所產生的任何錯誤或損害負責。Microsoft也同時將不斷地就機器翻譯軟體進行更新。

按一下這裡查看此文章的英文版本:190351
結論
本文將告訴您,如何重新導向輸入和輸出的子處理序,從標準輸入控制接收的輸入,或將輸出傳送到標準輸出控點。Win32 API 可讓子主控台處理序,以重新導向標準控點繁衍 (Spawn) 的應用程式。這項功能可讓父處理序來傳送和接收輸入和子處理序的輸出。

附註某些基礎的主控台應用程式不要為其輸入/輸出 (IO) 作業使用標準的控點。Win32 API 不支援這些程序的重新導向。
其他相關資訊
透過 STARTUPINFO 結構 CreateProcess() API 可讓您重新導向子主控台基礎程序的標準的控點。如果 dwFlags 成員設定為 [STARTF_USESTDHANDLES,然後下列 STARTUPINFO 成員指定子主控台基礎程序的標準的控點:
   HANDLE hStdInput - Standard input handle of the child process.   HANDLE hStdOutput - Standard output handle of the child process.   HANDLE hStdError - Standard error handle of the child process.				
您可以將這些控點設成任一個管道控制碼,檔案控制代碼,或者可以做同步任何控點讀取與寫入透過 ReadFile() 和 WriteFile() API。控點必須是可繼承,而且 CreateProcess() API 必須指定可繼承控制代碼是以繼承給子處理序,藉由在 bInheritHandles 參數中指定 TRUE。如果父處理序只想要重新導向一或兩個標準的控點,針對特定的控點指定 GetStdHandle() 導致子像平常一樣而重新導向不建立標準的控制代碼。比方說如果父處理序只需要重新導向標準輸出和子處理序錯誤,然後 STARTUPINFO 結構 hStdInput 成員會填滿,如下所示:
   hStdInput = GetStdHandle(STD_INPUT_HANDLE);				
重新導向時,可以不良行為作為 printf() 和 fprintf() 這類 C 執行階段函式的 附註 子處理序。C 執行階段函式會維護個別的 IO 緩衝區。時重新導向,每個 IO 呼叫之後立即可能不會清除這些緩衝區。如此一來從 getch() 呼叫重新導向管道 printf() 呼叫或輸入的輸出已不清空立即,並且延遲,有時無限延遲發生。如果子處理序清除 IO 緩衝區之每個 C 執行階段 IO 函式呼叫之後,會避免這個問題。子處理序可以排清其 C 執行階段 IO 緩衝區。處理程序可以藉由呼叫 fflush() 函式清除其 C 執行階段 IO 緩衝區。

附註Windows 95 和 Windows 98 需要額外的步驟,當您重新導向標準的控點的某些子處理程序。

下面的範例會將重新導向標準輸入、 輸出和子處理程序 CreateProcess 呼叫中指定的錯誤。這個範例會重新導向提供的主控台處理序 (Child.c)。

範例程式碼

   /*++      Copyright (c) 1998  Microsoft Corporation      Module Name:         Redirect.c      Description:          This sample illustrates how to spawn a child console based          application with redirected standard handles.          The following import libraries are required:          user32.lib      Dave McPherson (davemm)   11-March-98   --*/    #include<windows.h>   #pragma comment(lib, "User32.lib")   void DisplayError(char *pszAPI);   void ReadAndHandleOutput(HANDLE hPipeRead);   void PrepAndLaunchRedirectedChild(HANDLE hChildStdOut,                                     HANDLE hChildStdIn,                                     HANDLE hChildStdErr);   DWORD WINAPI GetAndSendInputThread(LPVOID lpvThreadParam);   HANDLE hChildProcess = NULL;   HANDLE hStdIn = NULL; // Handle to parents std input.   BOOL bRunThread = TRUE;   void main ()   {      HANDLE hOutputReadTmp,hOutputRead,hOutputWrite;      HANDLE hInputWriteTmp,hInputRead,hInputWrite;      HANDLE hErrorWrite;      HANDLE hThread;      DWORD ThreadId;      SECURITY_ATTRIBUTES sa;      // Set up the security attributes struct.      sa.nLength= sizeof(SECURITY_ATTRIBUTES);      sa.lpSecurityDescriptor = NULL;      sa.bInheritHandle = TRUE;      // Create the child output pipe.      if (!CreatePipe(&hOutputReadTmp,&hOutputWrite,&sa,0))         DisplayError("CreatePipe");      // Create a duplicate of the output write handle for the std error      // write handle. This is necessary in case the child application      // closes one of its std output handles.      if (!DuplicateHandle(GetCurrentProcess(),hOutputWrite,                           GetCurrentProcess(),&hErrorWrite,0,                           TRUE,DUPLICATE_SAME_ACCESS))         DisplayError("DuplicateHandle");      // Create the child input pipe.      if (!CreatePipe(&hInputRead,&hInputWriteTmp,&sa,0))         DisplayError("CreatePipe");      // Create new output read handle and the input write handles. Set      // the Properties to FALSE. Otherwise, the child inherits the      // properties and, as a result, non-closeable handles to the pipes      // are created.      if (!DuplicateHandle(GetCurrentProcess(),hOutputReadTmp,                           GetCurrentProcess(),                           &hOutputRead, // Address of new handle.                           0,FALSE, // Make it uninheritable.                           DUPLICATE_SAME_ACCESS))         DisplayError("DupliateHandle");      if (!DuplicateHandle(GetCurrentProcess(),hInputWriteTmp,                           GetCurrentProcess(),                           &hInputWrite, // Address of new handle.                           0,FALSE, // Make it uninheritable.                           DUPLICATE_SAME_ACCESS))      DisplayError("DupliateHandle");      // Close inheritable copies of the handles you do not want to be      // inherited.      if (!CloseHandle(hOutputReadTmp)) DisplayError("CloseHandle");      if (!CloseHandle(hInputWriteTmp)) DisplayError("CloseHandle");      // Get std input handle so you can close it and force the ReadFile to      // fail when you want the input thread to exit.      if ( (hStdIn = GetStdHandle(STD_INPUT_HANDLE)) ==                                                INVALID_HANDLE_VALUE )         DisplayError("GetStdHandle");      PrepAndLaunchRedirectedChild(hOutputWrite,hInputRead,hErrorWrite);      // Close pipe handles (do not continue to modify the parent).      // You need to make sure that no handles to the write end of the      // output pipe are maintained in this process or else the pipe will      // not close when the child process exits and the ReadFile will hang.      if (!CloseHandle(hOutputWrite)) DisplayError("CloseHandle");      if (!CloseHandle(hInputRead )) DisplayError("CloseHandle");      if (!CloseHandle(hErrorWrite)) DisplayError("CloseHandle");      // Launch the thread that gets the input and sends it to the child.      hThread = CreateThread(NULL,0,GetAndSendInputThread,                              (LPVOID)hInputWrite,0,&ThreadId);      if (hThread == NULL) DisplayError("CreateThread");      // Read the child's output.      ReadAndHandleOutput(hOutputRead);      // Redirection is complete      // Force the read on the input to return by closing the stdin handle.      if (!CloseHandle(hStdIn)) DisplayError("CloseHandle");      // Tell the thread to exit and wait for thread to die.      bRunThread = FALSE;      if (WaitForSingleObject(hThread,INFINITE) == WAIT_FAILED)         DisplayError("WaitForSingleObject");      if (!CloseHandle(hOutputRead)) DisplayError("CloseHandle");      if (!CloseHandle(hInputWrite)) DisplayError("CloseHandle");   }   ///////////////////////////////////////////////////////////////////////    // PrepAndLaunchRedirectedChild   // Sets up STARTUPINFO structure, and launches redirected child.   ///////////////////////////////////////////////////////////////////////    void PrepAndLaunchRedirectedChild(HANDLE hChildStdOut,                                     HANDLE hChildStdIn,                                     HANDLE hChildStdErr)   {      PROCESS_INFORMATION pi;      STARTUPINFO si;      // Set up the start up info struct.      ZeroMemory(&si,sizeof(STARTUPINFO));      si.cb = sizeof(STARTUPINFO);      si.dwFlags = STARTF_USESTDHANDLES;      si.hStdOutput = hChildStdOut;      si.hStdInput  = hChildStdIn;      si.hStdError  = hChildStdErr;      // Use this if you want to hide the child:      //     si.wShowWindow = SW_HIDE;      // Note that dwFlags must include STARTF_USESHOWWINDOW if you want to      // use the wShowWindow flags.      // Launch the process that you want to redirect (in this case,      // Child.exe). Make sure Child.exe is in the same directory as      // redirect.c launch redirect from a command line to prevent location      // confusion.      if (!CreateProcess(NULL,"Child.EXE",NULL,NULL,TRUE,                         CREATE_NEW_CONSOLE,NULL,NULL,&si,&pi))         DisplayError("CreateProcess");      // Set global child process handle to cause threads to exit.      hChildProcess = pi.hProcess;      // Close any unnecessary handles.      if (!CloseHandle(pi.hThread)) DisplayError("CloseHandle");   }   ///////////////////////////////////////////////////////////////////////    // ReadAndHandleOutput   // Monitors handle for input. Exits when child exits or pipe breaks.   ///////////////////////////////////////////////////////////////////////    void ReadAndHandleOutput(HANDLE hPipeRead)   {      CHAR lpBuffer[256];      DWORD nBytesRead;      DWORD nCharsWritten;      while(TRUE)      {         if (!ReadFile(hPipeRead,lpBuffer,sizeof(lpBuffer),                                          &nBytesRead,NULL) || !nBytesRead)         {            if (GetLastError() == ERROR_BROKEN_PIPE)               break; // pipe done - normal exit path.            else               DisplayError("ReadFile"); // Something bad happened.         }         // Display the character read on the screen.         if (!WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE),lpBuffer,                           nBytesRead,&nCharsWritten,NULL))            DisplayError("WriteConsole");      }   }   ///////////////////////////////////////////////////////////////////////    // GetAndSendInputThread   // Thread procedure that monitors the console for input and sends input   // to the child process through the input pipe.   // This thread ends when the child application exits.   ///////////////////////////////////////////////////////////////////////    DWORD WINAPI GetAndSendInputThread(LPVOID lpvThreadParam)   {      CHAR read_buff[256];      DWORD nBytesRead,nBytesWrote;      HANDLE hPipeWrite = (HANDLE)lpvThreadParam;      // Get input from our console and send it to child through the pipe.      while (bRunThread)      {         if(!ReadConsole(hStdIn,read_buff,1,&nBytesRead,NULL))            DisplayError("ReadConsole");         read_buff[nBytesRead] = '\0'; // Follow input with a NULL.         if (!WriteFile(hPipeWrite,read_buff,nBytesRead,&nBytesWrote,NULL))         {            if (GetLastError() == ERROR_NO_DATA)               break; // Pipe was closed (normal exit path).            else            DisplayError("WriteFile");         }      }      return 1;   }   ///////////////////////////////////////////////////////////////////////    // DisplayError   // Displays the error number and corresponding message.   ///////////////////////////////////////////////////////////////////////    void DisplayError(char *pszAPI)   {       LPVOID lpvMessageBuffer;       CHAR szPrintBuffer[512];       DWORD nCharsWritten;       FormatMessage(                FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,                NULL, GetLastError(),                MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),                (LPTSTR)&lpvMessageBuffer, 0, NULL);       wsprintf(szPrintBuffer,         "ERROR: API    = %s.\n   error code = %d.\n   message    = %s.\n",                pszAPI, GetLastError(), (char *)lpvMessageBuffer);       WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE),szPrintBuffer,                     lstrlen(szPrintBuffer),&nCharsWritten,NULL);       LocalFree(lpvMessageBuffer);       ExitProcess(GetLastError());   }   //////////////////////////////////////////////////////////////////////    // child.c   // Echoes all input to stdout. This will be redirected by the redirect   // sample. Compile and build child.c as a Win32 Console application and   // put it in the same directory as the redirect sample.   //    #include<windows.h>   #include<stdio.h>   #include<string.h>   void main ()   {      FILE*    fp;      CHAR     szInput[1024];      // Open the console. By doing this, you can send output directly to      // the console that will not be redirected.      fp = fopen("CON", "w");      if (!fp) {         printf("Error opening child console - perhaps there is none.\n");         fflush(NULL);      }      else      {      // Write a message direct to the console (will not be redirected).         fprintf(fp,"This data is being printed directly to the\n");         fprintf(fp,"console and will not be redirected.\n\n");         fprintf(fp,"Since the standard input and output have been\n");         fprintf(fp,"redirected data sent to and from those handles\n");         fprintf(fp,"will be redirected.\n\n");         fprintf(fp,"To send data to the std input of this process.\n");         fprintf(fp,"Click on the console window of the parent process\n");         fprintf(fp,"(redirect), and enter data from it's console\n\n");         fprintf(fp,"To exit this process send the string 'exit' to\n");         fprintf(fp,"it's standard input\n");         fflush(fp);      }      ZeroMemory(szInput,1024);      while (TRUE)      {         gets(szInput);         printf("Child echoing [%s]\n",szInput);         fflush(NULL);  // Must flush output buffers or else redirection                        // will be problematic.         if (!_stricmp(szInput,"Exit") )            break;         ZeroMemory(szInput,strlen(szInput) );      }   }
参考
MSDN 程式庫 SDK 文件: CreateProcess() ; STARTUPINFO 結構

繼承 Win32 平台 SDK 下的範例:
   \MSSDK\samples\winbase\ipc\inherit				
繼承重新導向的重新導向 stdhandles

警告:本文為自動翻譯

內容

文章識別碼:190351 - 最後檢閱時間:11/21/2006 15:28:50 - 修訂: 7.1

Microsoft Win32 Application Programming Interface

  • kbmt kbapi kbconsole kbfaq kbhowto kbipc kbkernbase KB190351 KbMtzh
意見反應
"76500"; var Ctrl = ""; document.write("