usustarr
usustarr

Reputation: 418

Programatically capture prints from child process at parent so they don't go to stdout

I do have a C++ program that runs on HPUX and Linux. My program creates 2 child process, parent waits for both child process to finish. When I execute my program form run directory as follows, run> myProgram

I get prints from both child process + parent process displayed. So I need to way to stop my child process to print onto the command prompt window. After child process are completed, I would like to turn on printing, so that parent can display the results.

Does anyone know how to turn on and turn off prints?

Upvotes: 1

Views: 560

Answers (1)

Julio Gorgé
Julio Gorgé

Reputation: 10106

Taking inspiration from 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");
}

Upvotes: 1

Related Questions