开发嵌入式设备的应用程序,有远程查看后台程序实时打印需求,小编提供一种这类例子解决问题方法,可以在任意的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
命令测试
结果如下图