当它要求输入时终止管道程序

时间:2013-10-05 14:26:27

标签: winapi pipe

当使用管道从生成的进程中读取时,是否可以在请求输入时终止所述程序?

如果它没有终止,通常的ReadFile循环直到管道关闭将永远阻塞:

tsi.cb := SizeOf(TStartupInfo);
tsi.dwFlags := STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW;
tsi.hStdInput := hInputRead;
tsi.hStdOutput := hOutputWrite;
tsi.hStdError := hErrorWrite;

if not CreateProcess(nil, PAnsiChar(Cmd), @sa, @sa, true, 0, nil, PAnsiChar(WorkDir), tsi, tpi) then
    exit;

// Close handles we don't need. We are only interested in its output
CloseHandle(hOutputWrite);
CloseHandle(hInputRead);
CloseHandle(hErrorWrite);

repeat
    // ReadFile will never return while our programs waits for input
    if not ReadFile(OutputRead, Buf, SizeOf(Buf), nRead, nil) or (nRead = 0) then
    begin
        if GetLastError = ERROR_BROKEN_PIPE then
            Break
        else
            ErrFunc('Pipe read error, could not execute file');
    end;

    // do something with buf...

until False;

单独终止非常容易(只使用TerminateProcess),但是只知道何时调用TerminateProcess太晚,即它挂起时。

1 个答案:

答案 0 :(得分:0)

首先,你没有使用Win32意义上的管道,你正在使用重定向的控制台输出 但是,如果等待超时,你可以wait on the file handle并中止。