以编程方式从父进程中的子进程捕获打印,以便它们不会转到stdout

时间:2011-04-25 20:52:23

标签: c++ linux process stdout hp-ux

我有一个在HPUX和Linux上运行的C ++程序。我的程序创建了2个子进程,父进程等待两个子进程完成。当我执行我的程序表单运行目录时,如下所示, 运行> myProgram

我从显示的子进程+父进程获得打印。所以我需要停止我的子进程打印到命令提示符窗口。子进程完成后,我想打开打印,以便父级可以显示结果。

有谁知道如何打开和关闭打印?

1 个答案:

答案 0 :(得分:1)

this answer获取灵感:

#include <stdio.h>

main()
{
    int    fd;
    fpos_t pos;

    printf("printing to stdout enabled\n");

    fflush(stdout);
    fgetpos(stdout, &pos);
    fd = dup(fileno(stdout));

    // Standard output redirected to the null device
    freopen("/dev/null", "w", stdout);

    f(); 

    // Standard output restored to its previous fd (the screen)
    fflush(stdout);
    dup2(fd, fileno(stdout));
    close(fd);
    clearerr(stdout);
    fsetpos(stdout, &pos);        /* for C9X */

    printf("printing to stdout enabled again\n");
}

f()
{
    printf("message sucked away by /dev/null");
}