2017-09-16 64 views
-1

我想發送一個程序,可能使用scanf,獲取或類似的東西,一些輸入通過使用winapi程序的管道。寫作似乎有效,但我必須做什麼才能讓其他程序讀取此輸入?讓scanf,從管道讀取等(WinAPI)

一個例子將是這樣的:

int main() 
{ 
HANDLE outputhandlewrite; 
HANDLE outputhandleread; 
HANDLE inputhandlewrite; 
HANDLE inputhandleread; 

char gdbpath = ".\SysGCC\bin\arm-linux-gnueabihf-gdb.exe"; 
char gdbcommand = "help"; 

SECURITY_ATTRIBUTES saAttr; 

PROCESS_INFORMATION piProcInfo; 
STARTUPINFO siStartInfo; 

BOOL bSuccess 

saAttr.nLength = sizeof(saAttr); 
saAttr.bInheritHandle = TRUE; 
saAttr.lpSecurityDescriptor = NULL; 

CreatePipe(&outputhandleread,&outputhandlewrite,&saAttr,0); 
SetHandleInformation(outputhandleread,HANDLE_FLAG_INHERIT,0); 
CreatePipe(&inputhandleread,&inputhandlewrite,&saAttr,0); 
SetHandleInformation(inputhandlewrite,HANDLE_FLAG_INHERIT,0); 

ZeroMemory(&piProcInfo,sizeof(piProcInfo)); 
ZeroMemory(siStartInfo,sizeof(siStartInfo)); 

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; 

CreateProcess(NULL,gdbpath,NULL,NULL,TRUE,0,NULL,NULL,&piProcInfo,&siStartInfo); 

for (;;) 
{ 
for (i = 0; i < (*ds).mds.mdscs.debuggerlineswidth; i++) 
{ 
    bSuccess = ReadFile((*ds).debuggeroutputdata.outputhandle, pipebuffer + i, 1, &bytesread, NULL); 

    if (*(pipebuffer + i) == '\r') 
    { 
     bSuccess = ReadFile((*ds).debuggeroutputdata.outputhandle, pipebuffer + i, 1, &bytesread, NULL); 
     break; 
    } 
} 

*(pipebuffer + i) = 0; 

//Here is just Code for printing the received ouput to the window 
} 

     bSuccess = WriteFile((*ds).debuggerinputdata.inputhandle, (*ds).debuggerinputdata.inputstring, strlen((*ds).debuggerinputdata.inputstring) + 1, &byteswritten, NULL); 
     bSuccess = WriteFile((*ds).debuggerinputdata.inputhandle, (*ds).debuggerinputdata.inputstring, 0, &byteswritten, NULL); 
} 

創建過程的工作,閱讀作品和WriteFile返回成功,寫入的字節等於所述輸入字符串的長度。 enter code here

+0

請編輯您的帖子以添加[mcve],以顯示您到目前爲止所提供的內容。 – zett42

+0

如果沒有[mcve]就很難說,但最可能的原因是(你在「答案」中給出了額外的信息)是你忘了發送一個行尾,或者沒有發送* right *線。我並不完全確定,但我認爲在這種情況下,您需要發送一個Windows結束行序列,即回車後跟一個換行符。 –

+1

[「在將進程的stdin和stdout重定向到管道時要小心,因爲您可能很容易死鎖」](https://blogs.msdn.microsoft.com/oldnewthing/20110707-00/?p=10223)。另外[「重定向輸出可能導致程序行爲改變」](https://blogs.msdn.microsoft.com/oldnewthing/20060519-09/?p=31133/)。 – zett42

回答

0

當您使用CreateProcess通過STARTUPINFO實例傳遞讀取的管道末端作爲標準輸入句柄。

如果我記得沒錯,你需要用可繼承的句柄創建管道。

+0

您當然不需要命名管道來重定向子進程。匿名管道就足夠了。 – zett42

+0

@ zett42 oops:我似乎總是忘記Win32也有這些:-)。 – Richard

+1

@ zett42 - 匿名管道與命名管道相同。同一個對象,只有沒有(從win7開始)或隨機名稱 – RbMm