You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C++中读取Go编译的exe的标准输出、输入与错误流?

Go编译程序与C++ Process类的管道交互异常问题

问题概述

我用C20实现了一个Process类,用于和外部可执行文件进行管道交互,对C编译的程序能正常工作,但启动Go编译的程序时,无法读取其标准输出、错误流,也无法向标准输入写入数据。不过Go进程能正常保持运行状态。

C++测试代码

// MultiTester.cpp
#include <iostream>
#include "Process.h"

int main()
{
    Process hello(1, "HelloWorld.exe"); hello.start();
    Process foo(2, "HelloFoo.exe"); foo.start();
    Process bar(3, "HelloBar.exe"); bar.start();

    std::string helloResponse = hello.readPipe(Process::OUTPUT);
    std::string fooResponse = foo.readPipe(Process::OUTPUT);
    std::string barResponse = bar.readPipe(Process::ERR);
    //Process::enum TYPE { INPUT, OUTPUT, ERR }; 也可以用 bar.ERR 这类写法
    //getHandle(TYPE type) 是公开方法,主要内部使用

    std::cout << helloResponse << std::endl;
    std::cout << fooResponse << std::endl;
    std::cout << barResponse << std::endl;

    //暂停执行
    std::cout << "Press character and Enter to end" << std::endl;
    std::string enter; std::cin >> enter;

    //关闭所有进程
    hello.writePipe(enter); 
    foo.writePipe(enter); 
    bar.writePipe(enter); 

    exit(0);
}

当目标程序是C编译时,测试程序能正常读取到"Hello World"、"Hello Foo"和"Hello Bar"(其中HelloBar.exe向std::cerr输出内容),三个C程序均以cin::get()结束运行。

Go测试代码

package main
import (
    "bufio"
    "fmt"
    "os"
)
func main() {
    fmt.Printf("hello world")
    fmt.Fprintln(os.Stdout,"hello foo")
    fmt.Fprintln(os.Stderr,"hello bar")
    
    in := bufio.NewScanner(os.Stdin)
    in.Scan()
}

我尝试了多种Go打印方式,但测试程序始终无法读取到任何输出,也无法向其输入数据。

补充背景

Process类基于微软官方的子进程管道重定向示例实现,之前测试C++编写的ConsoleCalculator.exe能通过该Process类正常交互,但Go版本的程序不行。Process类代码可在我的项目仓库中查看。


内容的提问来源于stack exchange,提问作者Akadine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 14:50:12