如何将STDIN传递给子进程?

whi*_*pps 9 c c++ winapi cmd process

cmd_more

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;

}
Run Code Online (Sandbox Code Playgroud)

主要(不完整):

while (1)
{
    Sleep(500);

    ReadFromPipe(); 

    WriteToPipe();


}
Run Code Online (Sandbox Code Playgroud)

我试图打开cmd作为子进程并将父输入传递给子STDIN流,而不是打印子进程的STDOUT.

正如你所看到的,它是第一次有效,但后来我得到了"更多?" 从子进程(cmd)返回,然后它等待输出卡住.

为什么我会"更多"?背部?

什么是"更多?"

Evg*_*nov 2

我发现重定向父输入的唯一方法是创建一个附加线程。常见的算法是:

  1. 创建管道 - ( hPipeRead, hPipeWrite)
  2. 使用标准输入创建子进程 -hPipeRead
  3. GetStdHandle(STD_INPUT_HANDLE)在正在读取并立即写入读取缓冲区的父进程中创建新线程hPipeWrite。当 stdInput 结束时,线程完成。
  4. 父进程正在等待附加线程

Microsoft 支持文章中描述了这种方式。