首页 > 解决方案 > 如何正确实现管道以与 Windows C++ 上的可执行文件进行通信?

问题描述

我有两个程序。以下代码是我在将方法实施到我的主程序之前想出的一个示例,以了解基础知识。子进程不可编辑并且是可执行文件(因为我无权访问我的主程序的源代码)。我的示例的子进程代码的代码:

#include <iostream>
#include <string>

using namespace std;

bool is_number(const std::string& s)
{
    string::const_iterator it = s.begin();
    while (it != s.end() && std::isdigit(*it)) ++it;
    return !s.empty() && it == s.end();
}

int main() {
    cout << "Enter some positive numbers" << endl;
    string testInput = "";

    while(true) {
        cin >> testInput;
        if(is_number(testInput)) {
            testInput += " is a positive number";
            cout << testInput << endl;
        }
        else {
            cout << "invalid" << endl;
        }
    }

    return EXIT_SUCCESS;                              //never exits
}

父函数的代码:

#include <cstdio>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <cstring>
#include <array>

std::string exec(const char* cmd) {
    std::array<char, 128> buffer;
    std::string result;
    std::unique_ptr<FILE, decltype(&_pclose)> pipe(_popen(cmd, "r"), _pclose);
    if (!pipe) {
        throw std::runtime_error("popen() failed!");
    }
    for (int returnNum = 0; returnNum < 5; returnNum++) {
        if(fgets(buffer.data(), buffer.size(), pipe.get()) == nullptr)
            break;
        result += buffer.data();
    }
    return result;
}

int main() {
    std::cout << "Result: " << exec(".\\child.exe") << "." << std::endl;

    system("PAUSE");
    return EXIT_SUCCESS;
}

父函数代码改编自如何使用 POSIX 在 C++ 中执行命令并获取命令输出的答案?. 我的理解是父函数打开可执行文件并允许我通过父函数命令行发送命令(不确定这些是如何传递给子进程的,但它确实有效)。如果子函数不在无限循环中,则结果将打印到父终端。

请注意,我总是需要调用子函数已知次数(因此是 for 循环)。我也不需要完美的代码,因为它只是我使用该程序。

为什么即使在 5 个命令之后也没有返回结果?如何让结果返回?如何在父程序的代码中发送命令,而不是将它们输入到父函数的终端中?

标签: c++pipeipc

解决方案


推荐阅读