【发布时间】:2017-09-16 07:00:51
【问题描述】:
我想发送一个程序,它可能使用 scanf、gets 或类似的东西,通过使用来自 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
【问题讨论】:
-
请编辑您的帖子以添加minimal reproducible example,以显示您到目前为止的想法。
-
没有minimal reproducible example 很难判断,但最可能的原因(鉴于您的“答案”中的附加信息)是您忘记发送行尾,或者没有发送 right 行尾。我不完全确定,但我认为在这种情况下,您需要发送 Windows 行尾序列,即回车后跟换行符。
-
这个support page 有更多信息以及一个更好的例子,它使用线程为子进程提供输入,Raymond Chen 在上面的第一个链接中也提出了这一建议。
-
对于你使用 2 对管道的情况,当足够时使用单管道对。为了避免死锁,最好使用异步 io 来处理管道