【linux笔记1.1】打印调试.如何将打印内容输出到另一个终端设备

问题描述

  在团队协作大型程序开发时,由于各个模块都可能存在大量打印,这时候终端上就会显示一堆打印。如果只想看到自己的打印而又不影响其他人的程序 那该怎么办呢?
  在linux系统中,每个终端都是一个设备文件,我们可以另起一个终端,在程序中open这个终端设备的文件号,然后将printf的内容都打印到这个终端设备上即可。

代码示例

添加下面代码到main.cpp中

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdarg.h>

int ALG_PRINT(char *fmt, ...)
{
    static int pts_fd = -1;
    char sprint_buf[1024] = {0};
    if (-1 == pts_fd)
    {
        pts_fd = open("/dev/pts/23", O_CREAT | O_WRONLY, 0666);
    }
        va_list args;
        int n;
        va_start(args, fmt);
        n = vsprintf(sprint_buf, fmt, args);
        va_end(args);
        if (-1 == pts_fd)
        {
            printf("%s", sprint_buf);
        }
        else
        {
            write(pts_fd, sprint_buf, n);
        }
        return n;
}

int main()
{
    ALG_PRINT("alg print test!\n");
    ALG_PRINT("a = %d, b = %s, afa!\n", 100, "test");
    return 0;
}

编译:g++ main.cpp

猜你喜欢

转载自blog.csdn.net/u011362297/article/details/80769914