createpipe function
創建匿名管道,返回讀,寫管道的handle。
BOOL WINAPI CreatePipe(
_Out_ PHANDLE hReadPipe,
_Out_ PHANDLE hWritePipe,
_In_opt_ LPSECURITY_ATTRIBUTES lpPipeAttributes,
_In_ DWORD nSize
);
參數:
hReadPipe [out]
返回對管道讀的handle
hWritePipe [out]
返回對管道寫的handle
lpPipeAttributes [in, optional]
指向SECURITY_ATTRIBUTES結構的指針。SECURITY_ATTRIBUTES決定了子進程是否可以繼承管道的讀寫handle。
如果lpPipeAttributes是NULL,不能繼承。
nSize [in]
管道的緩沖空間。只是一個建議值,系統會根據建議值計算出一個合適的值。如果nSize是0,使用缺省值。
返回值:
如果函數執行成功,返回值非0.
如果失敗,返回0??梢酝ㄟ^GetLastError獲得更多的信息。
說明:
CreatePipe創建包含適當大小緩沖空間的管道,返回通過ReadFile讀, WriteFile寫緩沖空間的handle.
ReadFile在如下情況返回:寫操作完成,已讀到請求大小的字節數,或者發生錯誤。
WriteFile只到寫完所有的字節數才會返回。
若管道緩沖空間在寫之前已經滿了,那么WriteFile將一直不會返回直到ReadFile讀管道后有足夠的緩沖空間。
匿名管道是通過命名管道實現的。因此,你可以把匿名管道handle作為命名管道handle使用。
為了釋放管道使用的資源,應用程序應該關閉那些不再使用的handles。
下面是子進程的代碼。它使用繼承的標準輸入STDIN和輸出STDOUT訪問父進程創建的管道。
父進程從in.txt讀數據,并把這些數據寫到管道1中。子進程從管道1中通過STDIN獲得數據,再通過STDOUT寫到管道2中。父進程之后再從管道2中讀取數據并顯示。
//client.cpp
#include <windows.h>
#include <stdio.h>
#define BUFSIZE 4096
int main(void)
{
CHAR chBuf[BUFSIZE];
DWORD dwRead, dwWritten;
HANDLE hStdin, hStdout;
BOOL bSuccess;
hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
hStdin = GetStdHandle(STD_INPUT_HANDLE);
if (
(hStdout == INVALID_HANDLE_VALUE) ||
(hStdin == INVALID_HANDLE_VALUE)
)
ExitProcess(1);
// Send something to this process's stdout using printf.
printf("\n ** This is a message from the child process. ** \n");
// This simple algorithm uses the existence of the pipes to control execution.
// It relies on the pipe buffers to ensure that no data is lost.
// Larger applications would use more advanced process control.
for (;;)
{
// Read from standard input and stop on error or no data.
bSuccess = ReadFile(hStdin, chBuf, BUFSIZE, &dwRead, NULL);
if (! bSuccess || dwRead == 0)
break;
// Write to standard output and stop on error.
bSuccess = WriteFile(hStdout, chBuf, dwRead, &dwWritten, NULL);
if (! bSuccess)
break;
}
return 0;
}
下面的示例展示了如何使用CreateProcess創建子進程。
同時展示了如何通過匿名管道重定向子進程的標準輸入和標準輸出。
命名管道同樣可以用于進程I/O的重定向。
CreatePipe函數使用SECURITY_ATTRIBUTES結構創建可繼承的handle。
這些管道指針在STARTUPINFO結構中被指定為子進程的標準輸入,輸出。
具體的,不妨參考in.txt上的一幅圖。
//parent.cpp
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <strsafe.h>
#define BUFSIZE 4096
HANDLE g_hChildStd_IN_Rd = NULL;
HANDLE g_hChildStd_IN_Wr = NULL;
HANDLE g_hChildStd_OUT_Rd = NULL;
HANDLE g_hChildStd_OUT_Wr = NULL;
HANDLE g_hInputFile = NULL;
void CreateChildProcess(void);
void WriteToPipe(void);
void ReadFromPipe(void);
void ErrorExit(PTSTR);
int _tmain(int argc, TCHAR *argv[])
{
SECURITY_ATTRIBUTES saAttr;
printf("\n->Start of parent execution.\n");
// Set the bInheritHandle flag so pipe handles are inherited.
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
// Create a pipe for the child process's STDOUT.
if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0) )
ErrorExit(TEXT("StdoutRd CreatePipe"));
// Ensure the read handle to the pipe for STDOUT is not inherited.
if ( ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0) )
ErrorExit(TEXT("Stdout SetHandleInformation"));
// Create a pipe for the child process's STDIN.
if (! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0))
ErrorExit(TEXT("Stdin CreatePipe"));
// Ensure the write handle to the pipe for STDIN is not inherited.
if ( ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
ErrorExit(TEXT("Stdin SetHandleInformation"));
// Create the child process.
// g_hChildStd_OUT_Wr and g_hChildStd_IN_Rd will be inherited by child
CreateChildProcess();
// Get a handle to an input file for the parent.
// This example assumes a plain text file and uses string output to verify data flow.
if (argc == 1)
ErrorExit(TEXT("Please specify an input file.\n"));
g_hInputFile = CreateFile(
argv[1],
GENERIC_READ,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_READONLY,
NULL);
if ( g_hInputFile == INVALID_HANDLE_VALUE )
ErrorExit(TEXT("CreateFile"));
// Write to the pipe that is the standard input for a child process.
// Data is written to the pipe's buffers, so it is not necessary to wait
// until the child process is running before writing data.
WriteToPipe();
printf( "\n->Contents of %s written to child STDIN pipe.\n", argv[1]);
// Read from pipe that is the standard output for child process.
printf( "\n->Contents of child process STDOUT:\n\n", argv[1]);
ReadFromPipe();
printf("\n->End of parent execution.\n");
// The remaining open handles are cleaned up when this process terminates.
// To avoid resource leaks in a larger application, close handles explicitly.
return 0;
}
void CreateChildProcess()
// Create a child process that uses the previously created pipes for STDIN and STDOUT.
{
TCHAR szCmdline[]=TEXT("child");
PROCESS_INFORMATION piProcInfo;
STARTUPINFO siStartInfo;
BOOL bSuccess = FALSE;
// Set up members of the PROCESS_INFORMATION structure.
ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
// Set up members of the STARTUPINFO structure.
// This structure specifies the STDIN and STDOUT handles for redirection.
ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
siStartInfo.cb = sizeof(STARTUPINFO);
siStartInfo.hStdError = g_hChildStd_OUT_Wr;
siStartInfo.hStdOutput = g_hChildStd_OUT_Wr;
siStartInfo.hStdInput = g_hChildStd_IN_Rd;
siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
// Create the child process.
bSuccess = CreateProcess(NULL,
szCmdline, // command line
NULL, // process security attributes
NULL, // primary thread security attributes
TRUE, // handles are inherited
0, // creation flags
NULL, // use parent's environment
NULL, // use parent's current directory
&siStartInfo, // STARTUPINFO pointer
&piProcInfo); // receives PROCESS_INFORMATION
// If an error occurs, exit the application.
if ( ! bSuccess )
ErrorExit(TEXT("CreateProcess"));
else
{
// Close handles to the child process and its primary thread.
// Some applications might keep these handles to monitor the status
// of the child process, for example.
CloseHandle(piProcInfo.hProcess);
CloseHandle(piProcInfo.hThread);
}
}
void WriteToPipe(void)
// Read from a file and write its contents to the pipe for the child's STDIN.
// Stop when there is no more data.
{
DWORD dwRead, dwWritten;
CHAR chBuf[BUFSIZE];
BOOL bSuccess = FALSE;
for (;;)
{
bSuccess = ReadFile(g_hInputFile, chBuf, BUFSIZE, &dwRead, NULL);
if ( ! bSuccess || dwRead == 0 ) break;
bSuccess = WriteFile(g_hChildStd_IN_Wr, chBuf, dwRead, &dwWritten, NULL);
if ( ! bSuccess ) break;
}
// Close the pipe handle so the child process stops reading.
if ( ! CloseHandle(g_hChildStd_IN_Wr) )
ErrorExit(TEXT("StdInWr CloseHandle"));
}
void ReadFromPipe(void)
// Read output from the child process's pipe for STDOUT
// and write to the parent process's pipe for STDOUT.
// Stop when there is no more data.
{
DWORD dwRead, dwWritten;
CHAR chBuf[BUFSIZE];
BOOL bSuccess = FALSE;
HANDLE hParentStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
for (;;)
{
bSuccess = ReadFile( g_hChildStd_OUT_Rd, chBuf, BUFSIZE, &dwRead, NULL);
if( ! bSuccess || dwRead == 0 ) break;
bSuccess = WriteFile(hParentStdOut, chBuf,
dwRead, &dwWritten, NULL);
if (! bSuccess ) break;
}
}
void ErrorExit(PTSTR lpszFunction)
// Format a readable error message, display a message box,
// and exit from the application.
{
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );
lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
(lstrlen((LPCTSTR)lpMsgBuf)+lstrlen((LPCTSTR)lpszFunction)+40)*sizeof(TCHAR));
StringCchPrintf((LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf) / sizeof(TCHAR),
TEXT("%s failed with error %d: %s"),
lpszFunction, dw, lpMsgBuf);
MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK);
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
ExitProcess(1);
}
//in.txt
/*Creating a Child Process with Redirected Input and Output
The example in this topic demonstrates how to create a child process
using the CreateProcess 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.
PipServer PipClient
g_hChildStd_IN_Wr g_hChildStd_IN_Rd/STD_INPUT_HANDLE
|----------------------->
anonymous pipe
<-----------------------|
g_hChildStd_OUT_Rd g_hChildStd_OUT_Wr/STD_OUTPUT_HANDLE*/
說明
1, http://msdn.microsoft.com/en-us/library/windows/desktop/aa365152(v=vs.85).aspx
2,http://msdn.microsoft.com/en-us/library/windows/desktop/ms682499(v=vs.85).aspx
本文由 貴州做網站公司 整理發布,部分圖文來源于互聯網,如有侵權,請聯系我們刪除,謝謝!
網絡推廣與網站優化公司(網絡優化與推廣專家)作為數字營銷領域的核心服務提供方,其價值在于通過技術手段與策略規劃幫助企業提升線上曝光度、用戶轉化率及品牌影響力。這...
在當今數字化時代,公司網站已成為企業展示形象、傳遞信息和開展業務的重要平臺。然而,對于許多公司來說,網站建設的價格是一個關鍵考量因素。本文將圍繞“公司網站建設價...
在當今的數字化時代,企業網站已成為企業展示形象、吸引客戶和開展業務的重要平臺。然而,對于許多中小企業來說,高昂的網站建設費用可能會成為其發展的瓶頸。幸運的是,隨...
郵件中的抄送和密送是什么意思?CC和BCC的區別如下:1。抄送是將電子郵件同時發送給收件人以外的其他人。用戶寫的郵件會被復制給他人,對方可以看到用戶的郵件。2. 在密件抄送(BCC)中,只有發送者知道消息被發送給了誰。接收者和抄送者都不知道發送者將消息發送給了誰。然而,接收者知道誰向他發送了消息,消息最初被發送給了誰,并且抄送,但是他不知道消息同時被發送給了誰。3. 例如,a向B1、B2、B3、C...
天津山地自行車批發市場在哪?天津民權門批發市場,叫天津北自行車商城,全是電動車,就在金鐘赫立交橋前面,609路:廣海廟到江路,633路,646路下車誰知道天津市內哪里有比較大的自行車批發市場?河北區的關羽路和南口路是天津自行車一條街的所在地,這里大概有幾十家自行車店,大部分都是自行車廠家的銷售點,正規而且很便宜(可以砍價)。等級都有,過了北洋橋就行,離江不遠。天津哪有專門賣自行車的大型市場?自行車...
安徽路 安霍邱縣郵政編碼237400霍邱縣區號0564六安的郵政編碼?魯郵政編碼;;安徽省安市237000郵政編碼行政區231300舒城縣陸 安徽省安市壽縣路232200。;安徽省安市237000金安區安路。;安徽省安市霍山縣路237200。;安徽省安市金寨縣路237300。;安徽省安市237400霍邱縣陸路。;安徽省安市。魯霍邱縣潘集鄉的郵政編碼。;安徽省安市,安徽省六安市霍邱縣潘集鄉郵編是什么...