【问题标题】:CreateProcess and redirecting outputCreateProcess 和重定向输出
【发布时间】:2017-09-22 09:32:47
【问题描述】:

有 2 个应用程序。

AppCMD 是一个命令行应用程序,AppMAIN 以一些命令行参数启动 AppCMD。 不幸的是,AppMAIN 似乎无法很好地处理AppCMD 的输出,并且出现了问题。

我想记录对AppCMD 的调用及其输出,看看发生了什么。

为此,我想用另一个二进制文件AppWRAP 替换AppCMD,它将调用转发到重命名的AppCMD 并记录它的输出。 AppWRAP 应该像一个透明的中间人。

出于测试目的,我写了一个简单的AppCMD,它只输出它的命令行参数:

#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    cout << "#### Hello, I'm the test binary that wants to be wrapped." << endl;

    if (argc < 2) {
        cout << "#### There where no command line arguments." << endl;
    }
    else {
        cout << "#### These are my command line arguments:";
        for (int i = 1; i < argc; ++i) cout << " " << argv[i];
        cout << endl;
    }

    cout << "#### That's pretty much everything I do ... yet ;)" << endl;

    return 0;
}

我按照MSDN: Creating a Child Process with Redirected Input and Output 实现AppWrap,但由于它没有返回而我被卡住了,我不知道为什么:

#include <iostream>
#include <sstream>
#include <Windows.h>


using namespace std;


const string TARGET_BINARY("TestBinary.exe");
const size_t BUFFSIZE = 4096;

HANDLE in_read        = 0;
HANDLE in_write       = 0;
HANDLE out_read       = 0;
HANDLE out_write      = 0;

int main(int argc, char *argv[])
{
    stringstream call;

    cout << "Hello, I'm BinTheMiddle." << endl;

//-------------------------- CREATE COMMAND LINE CALL --------------------------

    call << TARGET_BINARY;
    for (int i = 1; i < argc; ++i) {
        call << " " << argv[i];
    }

    cout << "Attempting to call '" << call.str() << "'" << endl;

//------------------------------ ARRANGE IO PIPES ------------------------------

    SECURITY_ATTRIBUTES security;
    security.nLength              = sizeof(SECURITY_ATTRIBUTES);
    security.bInheritHandle       = NULL;
    security.bInheritHandle       = TRUE;
    security.lpSecurityDescriptor = NULL;

    if (!CreatePipe(&out_read, &out_write, &security, 0)) {
        cout << "Error: StdoutRd CreatePipe" << endl;
        return -1;
    }
    if (!SetHandleInformation(out_read, HANDLE_FLAG_INHERIT, 0)) {
        cout << "Stdout SetHandleInformation" << endl;
        return -2;
    }
    if (!CreatePipe(&in_read, &in_write, &security, 0)) {
        cout << "Stdin CreatePipe" << endl;
        return -3;
    }
    if (!SetHandleInformation(in_write, HANDLE_FLAG_INHERIT, 0)) {
        cout << "Stdin SetHandleInformation" << endl;
        return -4;
    }
//------------------------------ START TARGET APP ------------------------------

    STARTUPINFO         start;
    PROCESS_INFORMATION proc;

    ZeroMemory(&start, sizeof(start));
    start.cb         = sizeof(start);
    start.hStdError  = out_write;
    start.hStdOutput = out_write;
    start.hStdInput  = in_read;
    start.dwFlags    |= STARTF_USESTDHANDLES;

    ZeroMemory(&proc, sizeof(proc));

    // Start the child process.
    if (!CreateProcess(NULL, (LPSTR) call.str().c_str(), NULL, NULL, TRUE,
                       0, NULL, NULL, &start, &proc))
    {
        cout << "CreateProcess failed (" << GetLastError() << ")" << endl;
        return -1;
    }

    // Wait until child process exits.
    WaitForSingleObject(proc.hProcess, INFINITE);
    // Close process and thread handles.
    CloseHandle(proc.hProcess);
    CloseHandle(proc.hThread);

//----------------------------------- OUTPUT -----------------------------------

    DWORD dwRead;
    CHAR  chBuf[127];

    while (ReadFile(out_read, chBuf, 127, &dwRead, NULL)) {
        cout << "Wrapped: " << chBuf << endl;
    }

    return 0;
}

它似乎在等待ReadFile 返回。谁能发现我做错了什么?

我这样称呼二进制文件:

> shell_cmd_wrapper.exe param1 param2

这是控制台输出,但二进制文件没有返回。

Hello, I'm BinTheMiddle.
Attempting to call 'TestBinary.exe param1 param2'
Wrapped:#### Hello, I'm the test binary that wants to be wrapped.
#### These are my command line arguments: param1 param2
#### That'sD
Wrapped: pretty much everything I do ... yet ;)
s to be wrapped.
#### These are my command line arguments: param1 param2
#### That'sD

(请忽略我没有清除缓冲区)

【问题讨论】:

  • 您可能需要在阅读之前使用PeekNamedPipe 来确定可用数据的大小。
  • @eryksun 谢谢。我打电话给CloseHandle(out_write); CloseHandle(in_read); 它似乎做了它应该做的事情:) 当你有计划写一个答案时,我计划接受一个答案。
  • 附带说明,在ReadFile() 之后,您应该向chBuf 添加一个空终止符,因为ReadFile 不会这样做。您可能很幸运 chBuf 最初用零填充,但它也可能是随机数据,因此 cout 会在实际字符串之后写入垃圾,甚至崩溃。
  • CHAR chBuf[127+1]; while (ReadFile(out_read, chBuf, 127, &amp;dwRead, NULL)) { chBuf[dwRead] = 0; cout &lt;&lt; "Wrapped: " &lt;&lt; chBuf &lt;&lt; endl; } - 请注意,我还将缓冲区大小增加了 1 以为空终止符腾出空间。
  • @zett42: 或者,您可以使用cout.write() 而不是cout &lt;&lt;,那么您根本不需要使用空终止符:cout &lt;&lt; "Wrapped: "; cout.write(chBuf, dwRead); cout &lt;&lt; endl;

标签: c++ windows winapi cmd


【解决方案1】:

在调用CreateProcess 后关闭out_write 和in_read 句柄。否则,out_read 上的 ReadFile 将在管道为空时阻塞,因为即使在子进程退出后仍有潜在的写入者——当前进程中的 out_write 句柄。

此外,正如 Harry Johnston 在评论中所指出的,在从管道读取之前等待进程退出可能会导致死锁。如果管道被填满,孩子将阻塞WriteFile。

【讨论】:

  • 当管道末端的 last 句柄关闭时 - 另一个管道末端将断开连接。 ReadFile 返回 FALSE 和 GetLastError 返回 ERROR_BROKEN_PIPE。 OP 有 2 个用于管道末端的句柄 - 在子进程和父进程中。当子退出时-其中的句柄已关闭,但子句中仍存在活动句柄。所以另一端没有断开,ReadFile 不会返回。关闭父级中的附加句柄可解决此问题。我们也可以创建 1 个管道对而不是 2 个。
  • @RbMm,假设句柄 out_write 句柄已关闭,OP 会忽略来自 ReadFile 的错误,当孩子退出时,它将是 ERROR_BROKEN_PIPE。最好检查一下这种情况,以免默默地忽略其他错误。我不知道你为什么说只需要 1 个管道,如果这就是“管道对”的意思。 OP 也在设置标准输入。我们没有看到使用它的代码,但需要它来驱动 AppCMD 的输入。那么死锁又是一个问题,用另一个线程最容易解决。
  • ReadFile 不返回,因为子退出时管道端未断开连接 - 在父进程中仍然存在此端的句柄。当我们关闭它时 - 这解决了问题。大约1对-我的意思是只创建2个句柄-CreateNamedPipe(父句柄)+CreateFile(将其复制到子句并在父句中关闭)。这对工作来说已经足够了。机器人句柄必须具有读/写访问权限。但几乎都使用了 2 对(4 个手柄)
  • 关于这里众所周知的死锁 - 我总是只使用异步 io。在这没有任何死锁的情况下,我们不依赖于父子之间的读/写顺序。和 1 对(1 个手柄在paren + 1 个在孩子)足够了
  • @RbMm、CreatePipe 为您调用 NtCreateNamedPipe 和 NtOpenFile。如果您自己执行此操作,您仍然必须关闭继承或复制句柄的副本。但是通过手动调用CreateNamedPipe 和CreateFile,您可以选择使用异步I/O。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-02
  • 2011-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-13
相关资源
最近更新 更多