andruhovski icon

PipeDemo

andruhovski | PRO | 03/14/16 11:13:38 AM UTC | 0 ⭐ | 10300 šŸ‘ļø | Never ā° | []
C++ (WinAPI) |

0 B

|

None

|

0 šŸ‘

/

0 šŸ‘Ž

int _tmain(int argc, _TCHAR* argv[])
{
//create pipe for the console stdout
SECURITY_ATTRIBUTES sa;
ZeroMemory(&sa, sizeof(SECURITY_ATTRIBUTES));
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.bInheritHandle = true;
sa.lpSecurityDescriptor = NULL;
HANDLE ReadPipeHandle;
HANDLE WritePipeHandle; Ā  Ā  Ā  // not used here
if (!CreatePipe(&ReadPipeHandle, &WritePipeHandle, &sa, 0))
return -1;
Ā 
//Create a Console
STARTUPINFO si;
ZeroMemory(&si, sizeof(STARTUPINFO));
si.cb = sizeof(STARTUPINFO);
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
si.wShowWindow = SW_HIDE;
si.hStdOutput = WritePipeHandle;
si.hStdError = WritePipeHandle;
Ā 
PROCESS_INFORMATION pi;
ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
if (!CreateProcess(_T("c:\\Windows\\System32\\cmd.exe"), NULL, NULL, NULL, true, 0, NULL, NULL, &si, &pi))
return -1;
Ā 
//Read from pipe
char Data[1024];
ZeroMemory(Data, 1024);
for (;;)
{
DWORD BytesRead;
DWORD TotalBytes;
DWORD BytesLeft;
Ā 
//Check for the presence of data in the pipe
if (!PeekNamedPipe(ReadPipeHandle, Data, sizeof(Data), &BytesRead,
&TotalBytes, &BytesLeft)) return -1;
//If there is bytes, read them
if (BytesRead)
{
if (!ReadFile(ReadPipeHandle, Data, sizeof(Data) - 1, &BytesRead, NULL))
return -1;
puts(Data);
Ā 
}
else
{
//Is the console app terminated?
if (WaitForSingleObject(pi.hProcess, 0) == WAIT_OBJECT_0)break;
Ā 
}
}
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
CloseHandle(ReadPipeHandle);
CloseHandle(WritePipeHandle);
return 0;
}

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    šŸ‘

    /

    šŸ‘Ž

    
        
  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    šŸ‘

    /

    šŸ‘Ž