linux的tee命令怎么在代码里执行开启和关闭

因为用了三方库,所以有些错误信息只能直接打印到了控制台上显示,现在想把这些打印信息保存在文件里。
用了./main | tee log.txt命令执行后确实可行,但是怎么能在C++代码里实现对tee命令的开启与关闭,目前只能在控制台上操作。
例如说在代码里加一个if的判断,如果为true则执行tee log.txt的操作,如果为false则不执行。

bool flag=true;
if (flag) {
 system("./main | tee log.txt");
} else {
 system("./main");
}

仅供参考:

#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
pid_t rw_popen(char* cmd, FILE **rfile, FILE **wfile) {
    int pipefd[2],pipefd2[2]; //管道描述符
    pid_t pid; //进程描述符

    if (pipe(pipefd) < 0) //建立管道
    {
        printf("rw_popen() pipe create error/n");
        return 0;
    }
    if (pipe(pipefd2) < 0) //建立管道
    {
        printf("rw_popen() pipe create error/n");
        return 0;
    }

    pid = fork(); //建立子进程

    if (pid < 0)
    return 0;

    if (0 == pid) //子进程中
    {
        close(pipefd[0]);
        dup2(pipefd[1], 1);
        close(pipefd[1]);
        dup2(pipefd2[0], 0);
        close(pipefd2[0]);
        close(pipefd[1]);
        char *argv[] = { "/bin/sh", "-c", cmd, NULL };
        if (execvp("/bin/sh", argv) < 0) //用exec族函数执行命令
        exit(1);
    }

    close(pipefd[1]);
    *rfile = fdopen(pipefd[0], "r");
    close(pipefd2[0]);
    *wfile = fdopen(pipefd2[1], "w");
    return pid;
}
void rw_pclose(pid_t pid, FILE *rfile, FILE *wfile) {
    int status;
    waitpid(pid, &status, 0);
    fclose(rfile);
    fclose(wfile);
}
int main() {
    char buf1[1024];
    FILE *file1, *file2;
    pid_t pid;
    pid = rw_popen("sh", &file1, &file2);
    if (pid) {
        fputs("pwd;exit;\n",file2);
        fflush(file2);
        if (fgets(buf1, 1400, file1)) {
            puts(buf1);
        }
        rw_pclose(pid, file1, file2);
    }
    return 1;
}