- UID
- 1029342
- 性别
- 男
|
//创建 SECURITY_ATTRIBUTES 结构void CNoNamedPipeParentDlg::CreateSecurityAttributes(PSECURITY_ATTRIBUTES pSa){ //这里必须将 bInheritHandle 设置为 TRUE, //从而使得子进程可以继承父进程创建的匿名管道的句柄 pSa->bInheritHandle = TRUE; pSa->lpSecurityDescriptor = NULL; pSa->nLength = sizeof(SECURITY_ATTRIBUTES);} //用来初始化新进程的 STARTUPINFO 成员void CNoNamedPipeParentDlg::CreateStartUpInfo(LPSTARTUPINFO lpStartUpInfo){ memset(lpStartUpInfo, 0, sizeof(STARTUPINFO)); lpStartUpInfo->cb = sizeof(STARTUPINFO); lpStartUpInfo->dwFlags = STARTF_USESTDHANDLES; //子进程的标准输入句柄为父进程管道的读数据句柄 lpStartUpInfo->hStdInput = hPipeRead; //子进程的标准输出句柄为父进程管道的写数据句柄 lpStartUpInfo->hStdOutput = hPipeWrite; //子进程的标准错误处理句柄和父进程的标准错误处理句柄一致 lpStartUpInfo->hStdError = GetStdHandle(STD_ERROR_HANDLE);} //创建匿名管道void CNoNamedPipeParentDlg::CreateNoNamedPipe(void){ SECURITY_ATTRIBUTES sa; PROCESS_INFORMATION processInfo; STARTUPINFO startUpInfo; CreateSecurityAttributes(&sa); if(!CreatePipe(&hPipeRead, &hPipeWrite, &sa, 0)) { MessageBox(TEXT(" 创建匿名管道失败 ..."), TEXT("提示"), MB_ICONERROR); return; } CreateStartUpInfo(&startUpInfo); if(!CreateProcess(TEXT("NoNamedPipeChild.exe"), NULL, NULL, NULL, TRUE, CREATE_NEW_CONSOLE, NULL, NULL, &startUpInfo, &processInfo)) { CloseHandle(hPipeRead); CloseHandle(hPipeWrite); hPipeWrite = NULL; hPipeRead = NULL; MessageBox(TEXT(" 创建子进程失败 ..."), TEXT("提示"), MB_ICONERROR); return; } else { m_PipeIsCreated = TRUE; //对于 processInfo.hProcess 和 processInfo.hThread //这两个句柄不需要使用,所以释放资源 CloseHandle(processInfo.hProcess); CloseHandle(processInfo.hThread); }}
子进程实现:(简单 MFC 程序)
项目结构:
消息以及成员函数和成员变量的声明:
// 实现protected: HICON m_hIcon; // 生成的消息映射函数 virtual BOOL OnInitDialog(); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); DECLARE_MESSAGE_MAP()public: afx_msg void OnBnClickedBtnWritePipe(); afx_msg void OnBnClickedBtnReadPipe(); //保存从父进程得到针对于匿名管道的读写句柄 HANDLE hPipeRead; HANDLE hPipeWrite; //分别代表要从匿名管道中读的数据和要写到匿名管道中的数据 CString m_CStrWritePipe; CString m_CStrReadPipe; //子进程读取匿名管道 void ChildReadPipe(void); //子进程写匿名管道 void ChildWritePipe(void); //子进程获取从父进程处继承得到的关于匿名管道的读写句柄 void GetReadWriteHandleFromParent(void); //只需要获取一次匿名管道的读写句柄即可 BOOL m_IsGettedParentHandle;
消息映射表定义:
const int dataLength = 100; CNoNamedPipeChildDlg::CNoNamedPipeChildDlg(CWnd* pParent /*=NULL*/) : CDialogEx(CNoNamedPipeChildDlg::IDD, pParent) , m_CStrWritePipe(_T("")) , m_CStrReadPipe(_T("")){ m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); this->m_IsGettedParentHandle = FALSE;} void CNoNamedPipeChildDlg:oDataExchange(CDataExchange* pDX){ CDialogEx:oDataExchange(pDX); DDX_Text(pDX, IDC_EDIT_WRITE_PIPE, m_CStrWritePipe); DDX_Text(pDX, IDC_EDIT_READ_PIPE, m_CStrReadPipe);} BEGIN_MESSAGE_MAP(CNoNamedPipeChildDlg, CDialogEx) ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(ID_BTN_WRITE_PIPE, &CNoNamedPipeChildDlg::OnBnClickedBtnWritePipe) ON_BN_CLICKED(ID_BTN_READ_PIPE, &CNoNamedPipeChildDlg::OnBnClickedBtnReadPipe)END_MESSAGE_MAP() |
|