【问题标题】:Let scanf, gets etc. read from a pipe (WinAPI)让 scanf、gets 等从管道中读取(WinAPI)
【发布时间】: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

【问题讨论】:

标签: winapi pipe scanf


【解决方案1】:

当您使用CreateProcess 传递STARTUPINFO 实例时,将您从中读取的管道末端作为标准输入句柄传递。

如果我没记错的话,您需要创建带有可继承句柄的管道。

【讨论】:

  • 您当然不需要命名管道来重定向子进程。匿名管道就足够了。
  • @zett42 哎呀:我似乎总是忘记 Win32 也有这些 :-)。
  • @zett42 - 匿名管道这与命名管道相同。同一个对象,只是没有(从 win7 开始)或随机名称
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-25
  • 2010-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多