Windows匿名管道


Windows匿名管道實際上是普通管道,其行為與UNIX中的對應物類似:它們是單向的,並且在通訊程序之間採用父子關係。此外,可以使用普通的ReadFile()和WriteFile()函式來讀寫管道。Windows API使用CreatePipe()函式建立管道,該函式傳遞四個引數。這些引數為

  • 讀和

  • 寫管道提供單獨的控制代碼

  • STARTUPINFO結構的一個例項,用於指定子程序要繼承管道的控制代碼。

  • 可以指定管道的尺寸(以位元組為單位)。

與UNIX系統不同,Windows要求程式設計師指定子程序將繼承哪些屬性。這是透過首先初始化SECURITY_ATTRIBUTES結構(允許繼承控制代碼),然後將子程序的標準輸入或標準輸出控制代碼重定向到管道的讀或寫控制代碼來實現的。由於子程序將從管道讀取資料,因此父程序必須將子程序的標準輸入重定向到管道的讀控制代碼。由於管道是半雙工的,因此需要禁止子程序繼承管道的寫端。

在下面的程式碼中,我們可以看到一個父程序建立了一個匿名管道,用於與其子程序通訊:

示例

#include<stdio.h>
#include<stdlib.h>
#include<windows.h>
#define BUFFER SIZE 25
int main(VOID) {
   HANDLE ReadHandle, WriteHandle;
   STARTUPINFO si;
   PROCESS INFORMATION pi;
   char message[BUFFER SIZE] = "Greetings";
   DWORD written;
   /* set up security attributes to allow pipes to be inherited */
   SECURITY ATTRIBUTES sa = {sizeof(SECURITY ATTRIBUTES), NULL, TRUE};
   /* allocate memory */
   ZeroMemory(π, sizeof(pi));
   /* create the pipe */
   if (!CreatePipe(&ReadHandle, &WriteHandle, &sa, 0)) {
   fprintf(stderr, "Create Pipe Failed"); return 1; }
   /* establishing the START INFO structure for the child process*/
   GetStartupInfo(&si);
   si.hStdOutput = GetStdHandle(STD OUTPUT HANDLE);
   /* redirecting standard input to the read end of the pipe */
   si.hStdInput = ReadHandle;
   si.dwFlags = STARTF USESTDHANDLES;
   /* don’t allow the child inheriting the write end of pipe */
   SetHandleInformation(WriteHandle, HANDLE FLAG INHERIT, 0);
   /* create the child process */
   CreateProcess(NULL, "child.exe", NULL, NULL, TRUE, /* inherit handles */ 0, NULL, NULL, &si, π);
   /* close the unused end of the pipe */ CloseHandle(ReadHandle);
   /* the parent writes to the pipe */
   if(!WriteFile(WriteHandle, message, BUFFER SIZE, &written, NULL))
   fprintf(stderr, "Error writing to pipe.");
   /* close the write end of the pipe */ CloseHandle(WriteHandle);
   /* wait for the child to exit */ WaitForSingleObject(pi.hProcess,INFINITE);        
   CloseHandle(pi.hProcess);
   CloseHandle(pi.hThread);
   return 0;
}

Windows匿名管道 - 父程序

父程序首先關閉其未使用的管道讀端,然後寫入管道。從管道讀取資料的子程序顯示在下面的程式碼中:

#include<stdio.h>
#include<windows.h>
#define BUFFER SIZE 25
int main(VOID){
   HANDLE Readhandle;
   CHAR buffer[BUFFER SIZE];
   DWORD read;
   /* getting the read handle of the pipe */
   ReadHandle = GetStdHandle(STD INPUT HANDLE);
   /* the child reads from the pipe */
   if (ReadFile(ReadHandle, buffer, BUFFER SIZE, &read, NULL))
      printf("child read %s", buffer);
   else
      fprintf(stderr, "Error reading from pipe");
   return 0;
}

Windows匿名管道 - 子程序

更新於:2019年10月11日

954 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.