[英]How to pass STDIN to child process?
void WriteToPipe(void)
// Read from a file and write its contents to the pipe for the child's STDIN.
// Stop when there is no more data.
{
DWORD dwRead, dwWritten;
CHAR chBuf[BUFSIZE];
BOOL bSuccess = FALSE;
char * name = malloc(100);
fgets(name, 100, stdin);
bSuccess = WriteFile(g_hChildStd_IN_Wr, name, 10, &dwWritten, NULL);
if (!bSuccess)
ErrorExit("");
}
void ReadFromPipe(void)
// Read output from the child process's pipe for STDOUT
// and write to the parent process's pipe for STDOUT.
// Stop when there is no more data.
{
DWORD dwRead, dwWritten;
CHAR chBuf[BUFSIZE];
BOOL bSuccess = FALSE;
HANDLE hParentStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
bSuccess = ReadFile(g_hChildStd_OUT_Rd, chBuf, BUFSIZE, &dwRead, NULL);
if (!bSuccess || dwRead == 0)
return 100;
bSuccess = WriteFile(hParentStdOut, chBuf,
dwRead, &dwWritten, NULL);
if (!bSuccess)
return 101;
}
The main (not full): 主要(不完整):
while (1)
{
Sleep(500);
ReadFromPipe();
WriteToPipe();
}
I am trying to open the cmd as a child process and to pass the parent input to the child STDIN stream, and than to print the STDOUT of the child. 我试图打开cmd作为子进程并将父输入传递给子STDIN流,而不是打印子进程的STDOUT。
As you can see, it works at the first time but then I get this "more?" 正如你所看到的,它是第一次有效,但后来我得到了“更多?” back from the child process (the cmd) and then it gets stuck waiting for output.
从子进程(cmd)返回,然后它等待输出卡住。
Why am I getting this "more?" 为什么我会“更多”? back?
背部?
What is that "more?" 什么是“更多?”
The only way of the redirection of parent input which I found - is creation an additional thread. 我找到的父输入重定向的唯一方法是创建一个额外的线程。 The common algorithm is:
常见的算法是:
hPipeRead
, hPipeWrite
) hPipeRead
, hPipeWrite
) hPipeRead
hPipeRead
GetStdHandle(STD_INPUT_HANDLE)
and is writing read buffer to hPipeWrite
immediately. GetStdHandle(STD_INPUT_HANDLE)
新线程,并立即将读缓冲区写入hPipeWrite
。 Thread is completed when stdInput is over. This way is described in Microsoft support article . Microsoft支持文章中描述了这种方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.