利用管道重定向标准输入输出流

来源:互联网 发布:菲律宾网络彩票合法吗 编辑:程序博客网 时间:2024/05/17 02:13

应用程序默认标准输出流是stdout、stdin、stderror,stdout的默认操作是送到终端显示出来,windows系统下我们可以修改者已默认行为,将应用程序的输出重定向到一个管道内,这样我们可以在进程内调用其他进程时进行输入输出操作。代码如下:

<span style="white-space:pre"></span>SECURITY_ATTRIBUTES sa;HANDLE hRead,hWrite;sa.nLength = sizeof(SECURITY_ATTRIBUTES);sa.lpSecurityDescriptor = NULL;sa.bInheritHandle = TRUE;if (!CreatePipe(&hRead,&hWrite,&sa,0)) {return FALSE;}STARTUPINFO si;PROCESS_INFORMATION pi; si.cb = sizeof(STARTUPINFO);GetStartupInfo(&si); si.hStdError = hWrite;            //把创建进程的标准错误输出重定向到管道输入si.hStdOutput = hWrite;           //把创建进程的标准输出重定向到管道输入si.wShowWindow = SW_HIDE;si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;//关键步骤,CreateProcess函数参数意义请查阅MSDN//openssl rsautl -decrypt -in hello.en -inkey private.key -out hello.de//openssl rsautl -encrypt -in hello.txt -inkey public.key -pubin -out hello.enif (!CreateProcess(L"openssl.exe", L"openssl rsautl -decrypt -in hello.en -inkey private.key -out hello.de",NULL,NULL,TRUE,NULL,NULL,NULL,&si,&pi)) {CloseHandle(hWrite);CloseHandle(hRead);return FALSE;}CloseHandle(hWrite);char buffer[4096] = {0};          //用4K的空间来存储输出的内容,只要不是显示文件内容,一般情况下是够用了。DWORD bytesRead; while (true) {if (ReadFile(hRead,buffer,4095,&bytesRead,NULL) == NULL)break;}CloseHandle(hRead);return true;


0 0