草庐IT

c++ - CreateProcess 和重定向输出

coder 2024-06-09 原文

有 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

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

最佳答案

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

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

关于c++ - CreateProcess 和重定向输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46361415/

有关c++ - CreateProcess 和重定向输出的更多相关文章

  1. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  2. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  3. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

  4. ruby - 如何进行排列以有效地定制输出 - 2

    这是一道面试题,我没有答对,但还是很好奇怎么解。你有N个人的大家庭,分别是1,2,3,...,N岁。你想给你的大家庭拍张照片。所有的家庭成员都排成一排。“我是家里的friend,建议家庭成员安排如下:”1岁的家庭成员坐在这一排的最左边。每两个坐在一起的家庭成员的年龄相差不得超过2岁。输入:整数N,1≤N≤55。输出:摄影师可以拍摄的照片数量。示例->输入:4,输出:4符合条件的数组:[1,2,3,4][1,2,4,3][1,3,2,4][1,3,4,2]另一个例子:输入:5输出:6符合条件的数组:[1,2,3,4,5][1,2,3,5,4][1,2,4,3,5][1,2,4,5,3][

  5. ruby - 将 spawn() 的标准输出/标准错误重定向到 Ruby 中的字符串 - 2

    我想使用spawn(针对多个并发子进程)在Ruby中执行一个外部进程,并将标准输出或标准错误收集到一个字符串中,其方式类似于使用Python的子进程Popen.communicate()可以完成的操作。我尝试将:out/:err重定向到一个新的StringIO对象,但这会生成一个ArgumentError,并且临时重新定义$stdxxx会混淆子进程的输出。 最佳答案 如果你不喜欢popen,这是我的方法:r,w=IO.pipepid=Process.spawn(command,:out=>w,:err=>[:child,:out])

  6. ruby - 使用 `+=` 和 `send` 方法 - 2

    如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是:

  7. ruby - Ruby 是否使用 $stdout 来写入 puts 和 return 的输出? - 2

    我想知道Ruby用来在命令行打印这些东西的输出流:irb(main):001:0>a="test"=>"test"irb(main):002:0>putsatest=>nilirb(main):003:0>a=>"test"$stdout是否用于irb(main):002:0>和irb(main):003:0>?而且,在这两次调用之间,$stdout的值是否有任何变化?另外,有人能告诉我打印/写入这些内容的Ruby源代码吗? 最佳答案 是的。而且很容易向自己测试/证明。在命令行试试这个:ruby-e'puts"foo"'>test.

  8. ruby-on-rails - 无法在 Rails 助手中捕获 block 的输出 - 2

    我在使用自定义RailsFormBuilder时遇到了问题,从昨天晚上开始我就发疯了。基本上我想对我的构建器方法之一有一个可选block,以便我可以在我的主要content_tag中显示其他内容。:defform_field(method,&block)content_tag(:div,class:'field')doconcatlabel(method,"Label#{method}")concattext_field(method)capture(&block)ifblock_given?endend当我在我的一个Slim模板中调用该方法时,如下所示:=f.form_field:e

  9. ruby - 如何计算 Liquid 中的变量 +1 - 2

    我对如何计算通过{%assignvar=0%}赋值的变量加一完全感到困惑。这应该是最简单的任务。到目前为止,这是我尝试过的:{%assignamount=0%}{%forvariantinproduct.variants%}{%assignamount=amount+1%}{%endfor%}Amount:{{amount}}结果总是0。也许我忽略了一些明显的东西。也许有更好的方法。我想要存档的只是获取运行的迭代次数。 最佳答案 因为{{incrementamount}}将输出您的变量值并且不会影响{%assign%}定义的变量,我

  10. ruby-on-rails - 连接字符串时如何在 <%=%> block 内输出 html_safe? - 2

    考虑一下:现在这些情况:#output:http://domain.com/?foo=1&bar=2#output:http://domain.com/?foo=1&bar=2#output:http://domain.com/?foo=1&bar=2#output:http://domain.com/?foo=1&bar=2我需要用其他字符串输出URL。我如何保证&符号不会被转义?由于我无法控制的原因,我无法发送&。求助!把我的头发拉到这里:\编辑:为了澄清,我实际上有一个像这样的数组:@images=[{:id=>"fooid",:url=>"http://

随机推荐