Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1637490
  • 博文数量: 584
  • 博客积分: 13857
  • 博客等级: 上将
  • 技术积分: 11883
  • 用 户 组: 普通用户
  • 注册时间: 2009-12-16 09:34

分类: WINDOWS

2011-04-19 21:39:31

The example in this topic demonstrates how to create a child process using the function from a console process. It also demonstrates a technique for using anonymous pipes to redirect the child process's standard input and output handles. Note that named pipes can also be used to redirect process I/O.

The function uses the structure to create inheritable handles to the read and write ends of two pipes. The read end of one pipe serves as standard input for the child process, and the write end of the other pipe is the standard output for the child process. These pipe handles are specified in the structure, which makes them the standard handles inherited by the child process.

The parent process uses the opposite ends of these two pipes to write to the child process's input and read from the child process's output. As specified in the structure, these handles are also inheritable. However, these handles must not be inherited. Therefore, before creating the child process, the parent process uses the function to ensure that the write handle for the child process's standard input and the read handle for the child process's standard input cannot be inherited. For more information, see .

The following is the code for the parent process. It takes a single command-line argument: the name of a text file.

  1. #include <windows.h>
  2. #include <tchar.h>
  3. #include <stdio.h>
  4. #include <strsafe.h>

  5. #define BUFSIZE 4096
  6.  
  7. HANDLE g_hChildStd_IN_Rd = NULL;
  8. HANDLE g_hChildStd_IN_Wr = NULL;
  9. HANDLE g_hChildStd_OUT_Rd = NULL;
  10. HANDLE g_hChildStd_OUT_Wr = NULL;

  11. HANDLE g_hInputFile = NULL;
  12.  
  13. void CreateChildProcess(void);
  14. void WriteToPipe(void);
  15. void ReadFromPipe(void);
  16. void ErrorExit(PTSTR);
  17.  
  18. int _tmain(int argc, TCHAR *argv[])
  19. {
  20.    SECURITY_ATTRIBUTES saAttr;
  21.  
  22.    printf("\n->Start of parent execution.\n");

  23. // Set the bInheritHandle flag so pipe handles are inherited.
  24.  
  25.    saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
  26.    saAttr.bInheritHandle = TRUE;
  27.    saAttr.lpSecurityDescriptor = NULL;

  28. // Create a pipe for the child process's STDOUT.
  29.  
  30.    if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0) )
  31.       ErrorExit(TEXT("StdoutRd CreatePipe"));

  32. // Ensure the read handle to the pipe for STDOUT is not inherited.

  33.    if ( ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0) )
  34.       ErrorExit(TEXT("Stdout SetHandleInformation"));

  35. // Create a pipe for the child process's STDIN.
  36.  
  37.    if (! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0))
  38.       ErrorExit(TEXT("Stdin CreatePipe"));

  39. // Ensure the write handle to the pipe for STDIN is not inherited.
  40.  
  41.    if ( ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
  42.       ErrorExit(TEXT("Stdin SetHandleInformation"));
  43.  
  44. // Create the child process.
  45.    
  46.    CreateChildProcess();

  47. // Get a handle to an input file for the parent.
  48. // This example assumes a plain text file and uses string output to verify data flow.
  49.  
  50.    if (argc == 1)
  51.       ErrorExit(TEXT("Please specify an input file.\n"));

  52.    g_hInputFile = CreateFile(
  53.        argv[1],
  54.        GENERIC_READ,
  55.        0,
  56.        NULL,
  57.        OPEN_EXISTING,
  58.        FILE_ATTRIBUTE_READONLY,
  59.        NULL);

  60.    if ( g_hInputFile == INVALID_HANDLE_VALUE )
  61.       ErrorExit(TEXT("CreateFile"));
  62.  
  63. // Write to the pipe that is the standard input for a child process.
  64. // Data is written to the pipe's buffers, so it is not necessary to wait
  65. // until the child process is running before writing data.
  66.  
  67.    WriteToPipe();
  68.    printf( "\n->Contents of %s written to child STDIN pipe.\n", argv[1]);
  69.  
  70. // Read from pipe that is the standard output for child process.
  71.  
  72.    printf( "\n->Contents of child process STDOUT:\n\n", argv[1]);
  73.    ReadFromPipe();

  74.    printf("\n->End of parent execution.\n");

  75. // The remaining open handles are cleaned up when this process terminates.
  76. // To avoid resource leaks in a larger application, close handles explicitly.

  77.    return 0;
  78. }
  79.  
  80. void CreateChildProcess()
  81. // Create a child process that uses the previously created pipes for STDIN and STDOUT.
  82. {
  83.    TCHAR szCmdline[]=TEXT("child");
  84.    PROCESS_INFORMATION piProcInfo;
  85.    STARTUPINFO siStartInfo;
  86.    BOOL bSuccess = FALSE;
  87.  
  88. // Set up members of the PROCESS_INFORMATION structure.
  89.  
  90.    ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
  91.  
  92. // Set up members of the STARTUPINFO structure.
  93. // This structure specifies the STDIN and STDOUT handles for redirection.
  94.  
  95.    ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
  96.    siStartInfo.cb = sizeof(STARTUPINFO);
  97.    siStartInfo.hStdError = g_hChildStd_OUT_Wr;
  98.    siStartInfo.hStdOutput = g_hChildStd_OUT_Wr;
  99.    siStartInfo.hStdInput = g_hChildStd_IN_Rd;
  100.    siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
  101.  
  102. // Create the child process.
  103.     
  104.    bSuccess = CreateProcess(NULL,
  105.       szCmdline, // command line
  106.       NULL, // process security attributes
  107.       NULL, // primary thread security attributes
  108.       TRUE, // handles are inherited
  109.       0, // creation flags
  110.       NULL, // use parent's environment
  111.       NULL, // use parent's current directory
  112.       &siStartInfo, // STARTUPINFO pointer
  113.       &piProcInfo); // receives PROCESS_INFORMATION
  114.    
  115.    // If an error occurs, exit the application.
  116.    if ( ! bSuccess )
  117.       ErrorExit(TEXT("CreateProcess"));
  118.    else
  119.    {
  120.       // Close handles to the child process and its primary thread.
  121.       // Some applications might keep these handles to monitor the status
  122.       // of the child process, for example.

  123.       CloseHandle(piProcInfo.hProcess);
  124.       CloseHandle(piProcInfo.hThread);
  125.    }
  126. }
  127.  
  128. void WriteToPipe(void)

  129. // Read from a file and write its contents to the pipe for the child's STDIN.
  130. // Stop when there is no more data.
  131. {
  132.    DWORD dwRead, dwWritten;
  133.    CHAR chBuf[BUFSIZE];
  134.    BOOL bSuccess = FALSE;
  135.  
  136.    for (;;)
  137.    {
  138.       bSuccess = ReadFile(g_hInputFile, chBuf, BUFSIZE, &dwRead, NULL);
  139.       if ( ! bSuccess || dwRead == 0 ) break;
  140.       
  141.       bSuccess = WriteFile(g_hChildStd_IN_Wr, chBuf, dwRead, &dwWritten, NULL);
  142.       if ( ! bSuccess ) break;
  143.    }
  144.  
  145. // Close the pipe handle so the child process stops reading.
  146.  
  147.    if ( ! CloseHandle(g_hChildStd_IN_Wr) )
  148.       ErrorExit(TEXT("StdInWr CloseHandle"));
  149. }
  150.  
  151. void ReadFromPipe(void)

  152. // Read output from the child process's pipe for STDOUT
  153. // and write to the parent process's pipe for STDOUT.
  154. // Stop when there is no more data.
  155. {
  156.    DWORD dwRead, dwWritten;
  157.    CHAR chBuf[BUFSIZE];
  158.    BOOL bSuccess = FALSE;
  159.    HANDLE hParentStdOut = GetStdHandle(STD_OUTPUT_HANDLE);

  160. // Close the write end of the pipe before reading from the
  161. // read end of the pipe, to control child process execution.
  162. // The pipe is assumed to have enough buffer space to hold the
  163. // data the child process has already written to it.
  164.  
  165.    if (!CloseHandle(g_hChildStd_OUT_Wr))
  166.       ErrorExit(TEXT("StdOutWr CloseHandle"));
  167.  
  168.    for (;;)
  169.    {
  170.       bSuccess = ReadFile( g_hChildStd_OUT_Rd, chBuf, BUFSIZE, &dwRead, NULL);
  171.       if( ! bSuccess || dwRead == 0 ) break;

  172.       bSuccess = WriteFile(hParentStdOut, chBuf,
  173.                            dwRead, &dwWritten, NULL);
  174.       if (! bSuccess ) break;
  175.    }
  176. }
  177.  
  178. void ErrorExit(PTSTR lpszFunction)

  179. // Format a readable error message, display a message box,
  180. // and exit from the application.
  181. {
  182.     LPVOID lpMsgBuf;
  183.     LPVOID lpDisplayBuf;
  184.     DWORD dw = GetLastError();

  185.     FormatMessage(
  186.         FORMAT_MESSAGE_ALLOCATE_BUFFER |
  187.         FORMAT_MESSAGE_FROM_SYSTEM |
  188.         FORMAT_MESSAGE_IGNORE_INSERTS,
  189.         NULL,
  190.         dw,
  191.         MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  192.         (LPTSTR) &lpMsgBuf,
  193.         0, NULL );

  194.     lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
  195.         (lstrlen((LPCTSTR)lpMsgBuf)+lstrlen((LPCTSTR)lpszFunction)+40)*sizeof(TCHAR));
  196.     StringCchPrintf((LPTSTR)lpDisplayBuf,
  197.         LocalSize(lpDisplayBuf) / sizeof(TCHAR),
  198.         TEXT("%s failed with error %d: %s"),
  199.         lpszFunction, dw, lpMsgBuf);
  200.     MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK);

  201.     LocalFree(lpMsgBuf);
  202.     LocalFree(lpDisplayBuf);
  203.     ExitProcess(1);
  204. }

The following is the code for the child process. It uses the inherited handles for STDIN and STDOUT to access the pipe created by the parent. The parent process reads from its input file and writes the information to a pipe. The child receives text through the pipe using STDIN and writes to the pipe using STDOUT. The parent reads from the read end of the pipe and displays the information to its STDOUT.

  1. #include <windows.h>
  2. #include <stdio.h>

  3. #define BUFSIZE 4096
  4.  
  5. int main(void)
  6. {
  7.    CHAR chBuf[BUFSIZE];
  8.    DWORD dwRead, dwWritten;
  9.    HANDLE hStdin, hStdout;
  10.    BOOL bSuccess;
  11.  
  12.    hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
  13.    hStdin = GetStdHandle(STD_INPUT_HANDLE);
  14.    if (
  15.        (hStdout == INVALID_HANDLE_VALUE) ||
  16.        (hStdin == INVALID_HANDLE_VALUE)
  17.       )
  18.       ExitProcess(1);
  19.  
  20.    // Send something to this process's stdout using printf.
  21.    printf("\n ** This is a message from the child process. ** \n");

  22.    // This simple algorithm uses the existence of the pipes to control execution.
  23.    // It relies on the pipe buffers to ensure that no data is lost.
  24.    // Larger applications would use more advanced process control.

  25.    for (;;)
  26.    {
  27.    // Read from standard input and stop on error or no data.
  28.       bSuccess = ReadFile(hStdin, chBuf, BUFSIZE, &dwRead, NULL);
  29.       
  30.       if (! bSuccess || dwRead == 0)
  31.          break;
  32.  
  33.    // Write to standard output and stop on error.
  34.       bSuccess = WriteFile(hStdout, chBuf, dwRead, &dwWritten, NULL);
  35.       
  36.       if (! bSuccess)
  37.          break;
  38.    }
  39.    return 0;
  40. }
阅读(742) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~