C: 如何将 stderr 从系统命令重定向到 stdout 或文件?

标签 c stdout stderr file-descriptor

shell 命令 $ avrdude -c usbtiny 将文本输出到 stderr。我无法使用 head-less-more 之类的命令读取它,因为它不是标准输出。我希望文本输出到标准输出或文件。我怎样才能在 C 中做到这一点?我试图通过 my last question 解决问题但仍未解决。

最佳答案

我没有在 OpenBSD 中尝试过这样的事情,但至少在一些 *nix 类系统中,你可以使用 dup2 来做到这一点。

#include <unistd.h>
#include <stdio.h>

int main(void) {  

  fprintf(stderr, "This goes to stderr\n");

  dup2(1, 2);  //redirects stderr to stdout below this line.

  fprintf(stderr, "This goes to stdout\n");
}

关于C: 如何将 stderr 从系统命令重定向到 stdout 或文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3019630/

相关文章:

python - 如何悄悄启动Python REPL?

linux - 监视在我的 linux 机器上运行的所有进程的 STDERR

perl: IPC::Open3 无法使用 FCGI 打开 STDERR

c - 在 C 中以间隔执行特定语句,而其他语句保持运行

bash - 在 Bash 中连接字符串、文件和程序输出

计算均值中位数模式c编程数组

python - 关闭 python 命令子进程

C 程序结束时的错误处理

创建一个不可停止的程序

C 重新分配/malloc 替代