Advertisement
andruhovski

PipeDemo

Mar 14th, 2016
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. int _tmain(int argc, _TCHAR* argv[])
  2. {
  3. //create pipe for the console stdout
  4. SECURITY_ATTRIBUTES sa;
  5. ZeroMemory(&sa, sizeof(SECURITY_ATTRIBUTES));
  6. sa.nLength = sizeof(SECURITY_ATTRIBUTES);
  7. sa.bInheritHandle = true;
  8. sa.lpSecurityDescriptor = NULL;
  9. HANDLE ReadPipeHandle;
  10. HANDLE WritePipeHandle;       // not used here
  11. if (!CreatePipe(&ReadPipeHandle, &WritePipeHandle, &sa, 0))
  12. return -1;
  13.  
  14. //Create a Console
  15. STARTUPINFO si;
  16. ZeroMemory(&si, sizeof(STARTUPINFO));
  17. si.cb = sizeof(STARTUPINFO);
  18. si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
  19. si.wShowWindow = SW_HIDE;
  20. si.hStdOutput = WritePipeHandle;
  21. si.hStdError = WritePipeHandle;
  22.  
  23. PROCESS_INFORMATION pi;
  24. ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
  25. if (!CreateProcess(_T("c:\\Windows\\System32\\cmd.exe"), NULL, NULL, NULL, true, 0, NULL, NULL, &si, &pi))
  26. return -1;
  27.  
  28. //Read from pipe
  29. char Data[1024];
  30. ZeroMemory(Data, 1024);
  31. for (;;)
  32. {
  33. DWORD BytesRead;
  34. DWORD TotalBytes;
  35. DWORD BytesLeft;
  36.  
  37. //Check for the presence of data in the pipe
  38. if (!PeekNamedPipe(ReadPipeHandle, Data, sizeof(Data), &BytesRead,
  39. &TotalBytes, &BytesLeft)) return -1;
  40. //If there is bytes, read them
  41. if (BytesRead)
  42. {
  43. if (!ReadFile(ReadPipeHandle, Data, sizeof(Data) - 1, &BytesRead, NULL))
  44. return -1;
  45. puts(Data);
  46.  
  47. }
  48. else
  49. {
  50. //Is the console app terminated?
  51. if (WaitForSingleObject(pi.hProcess, 0) == WAIT_OBJECT_0)break;
  52.  
  53. }
  54. }
  55. CloseHandle(pi.hThread);
  56. CloseHandle(pi.hProcess);
  57. CloseHandle(ReadPipeHandle);
  58. CloseHandle(WritePipeHandle);
  59. return 0;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement