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

如何获取libpipeline中子进程的错误流管道?

如何通过libpipeline读取子进程的错误流?

我尝试通过libpipeline执行外部程序,但无法获取子进程的错误流。相关代码如下:

#include <pipeline.h>
#include <stdlib.h>
#include <stdio.h>
#include <pwd.h>
#include <unistd.h>
#include <string.h>

int main() {
    pipeline *cmd;
    const char *line;

    // get user info
    struct passwd *uinfo = getpwuid(geteuid());
    if (!uinfo) {
        perror(NULL);
        return EXIT_FAILURE;
    }
    printf("login shell: %s\n", uinfo->pw_shell);

    // Create the pipeline of the external application, NULL indicates the end of parameter input.
    cmd = pipeline_new_command_args(uinfo->pw_shell, "-c", "echo 'Hello World' 1>&2", NULL);
    pipeline_want_out(cmd, -1);
    pipeline_start(cmd);
    line = pipeline_peekline(cmd);
    if (!strstr(line, "coding: UTF-8")) printf("Unicode text follows:0\n");

    while ((line = pipeline_readline(cmd))) printf("stdout: %s", line);

    printf("exit code: %d\n", pipeline_wait(cmd));

    return EXIT_SUCCESS;
}

环境信息:

  • 操作系统:Linux 5.15.60-1-MANJARO
  • GCC版本:12.1.1 20220730 (GCC)
  • Shell:zsh 5.9

解决方案

要读取子进程的错误流,需利用libpipeline提供的错误流捕获和读取接口,具体调整如下:

  1. 启用错误流捕获:调用pipeline_want_err(cmd, -1),将子进程的stderr重定向到libpipeline的内部缓冲区,用法与pipeline_want_out()一致。
  2. 单独读取错误流:使用pipeline_readline_err()函数专门读取stderr内容,循环调用直到返回NULL表示流已耗尽。
  3. 调整读取顺序:先读完stdout,再读取stderr,确保所有输出都被捕获。

修改后的完整代码:

#include <pipeline.h>
#include <stdlib.h>
#include <stdio.h>
#include <pwd.h>
#include <unistd.h>
#include <string.h>

int main() {
    pipeline *cmd;
    const char *line;

    // 获取用户信息
    struct passwd *uinfo = getpwuid(geteuid());
    if (!uinfo) {
        perror(NULL);
        return EXIT_FAILURE;
    }
    printf("login shell: %s\n", uinfo->pw_shell);

    // 创建外部程序管道,NULL表示参数输入结束
    cmd = pipeline_new_command_args(uinfo->pw_shell, "-c", "echo 'Hello World' 1>&2", NULL);
    
    // 同时捕获stdout和stderr
    pipeline_want_out(cmd, -1);
    pipeline_want_err(cmd, -1);
    
    pipeline_start(cmd);

    // 读取标准输出
    while ((line = pipeline_readline(cmd))) {
        printf("stdout: %s", line);
    }

    // 读取标准错误
    while ((line = pipeline_readline_err(cmd))) {
        printf("stderr: %s", line);
    }

    printf("exit code: %d\n", pipeline_wait(cmd));

    return EXIT_SUCCESS;
}

关键说明

  • pipeline_want_err()是开启错误流捕获的核心函数,必须在pipeline_start()之前调用。
  • pipeline_readline_err()与pipeline_readline()对应,专门用于读取错误流内容。
  • 若需要同时监听两个流的实时输出,可结合非阻塞读取逻辑,但对于大多数场景,按顺序读取即可满足需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 12:58:01