一种查看嵌入式后台打印的解决方式

开发嵌入式设备的应用程序,有远程查看后台程序实时打印需求,小编提供一种这类例子解决问题方法,可以在任意的ssh会话里面获取后台程序的打印信息。

tty命令

tty命令在Linux系统中是一个用于查看和管理终端(TTY)设备的命令行工具。TTY是指终端设备,可以用于与计算机进行交互。输入该命令后,系统将返回当前正在使用的终端的名称,如下

$ tty
/dev/pts/0

代码例子

outPut命令的代码

/*outPut.c文件*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
    int tty = -1;
    char *tty_name = NULL;
    if(argc < 2)
    {
        printf("miss argument\n");
        return 0;
    }
    tty_name = ttyname(STDOUT_FILENO);  /* 获取当前tty名称 */
    printf("tty_name: %s\n", tty_name);
    if(!strcmp(argv[1], "open"))
    {
        tty = open(tty_name, O_RDONLY | O_WRONLY); /* 重定向console到当前tty */
        ioctl(tty, TIOCCONS);
        perror("ioctl TIOCCONS");
    }
    else if(!strcmp(argv[1], "close"))
    {
        tty = open("/dev/console", O_RDONLY | O_WRONLY); /* 恢复console */
        ioctl(tty, TIOCCONS);
        perror("ioctl TIOCCONS");
    }
    else
    {
        printf("error argument\n");
        return 0;
    }

    close(tty);
    return 0;
}

待测试命令文件

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main()
{
    int i = 0;
    // 打开串口设备
    int fd = open("/dev/console", O_RDWR | O_NOCTTY | O_NDELAY);
    if (fd == -1)
    {
        perror("无法打开串口");
        return 1;
    }
    // 重定向标准输出到串口
    if (dup2(fd, STDOUT_FILENO) == -1)
    {
        perror("重定向标准输出失败");
        close(fd);
        return 1;
    }
    // 测试输出
    while (1)
    {
        printf("++++++%d\n", i++);
        sleep(1);
    }
    // 关闭串口
    close(fd);
    return 0;
}

测试Makefile文件

all:
	gcc print.c -o print
	gcc outPut.c -o outPut
	g++ main.cpp -o main
	chmod +x print outPut main

命令测试

结果如下图
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值