一种将程序的标准输出重定向到telnet终端的方法

文章来源:http://blog.chinaunix.net/uid-23859284-id-5015284.html


在现场调试嵌入式设备时,很多时候我们是无法连接串口查看打印信息的,只可以通过网络连接telnet登陆到设备终端,

而此时是无法查看当前运行的应用程序的打印信息的,为我们排查问题带来了一定的困难。当然,我们可以通过gdb工具
attach进程进行调试,但这种方式还是比较麻烦的。我根据gdb的原理,实现了一个快速将应用程序标准输出打印到telnet
终端的工具。代码如下:
==================================================================================================
服务端程序
#include 

int stdio_redirect_daemon(char * tty)
{
    int ret = -1;
    if (tty == NULL)
    {
        printf("print_redirection,parameter is null.\n");
        return -1;
    } 
    close(1);
    close(2);
    ret = (int)open(tty, 1);
    if (ret < 0)
    {
        printf("redirect stdout to tty error:%s.\n", strerror(errno));
        return ret; 
    }
    ret = (int)open(tty, 2);
    if (ret < 0)
    {
        printf("redirect stderr to tty error:%s.\n", strerror(errno));
        return ret; 
    }
    fflush(NULL);
    return 0;
}


int main()
{
    char tty[32] = {0};
    //从客户端指定的文件中(/tmp/cttyname)读取
    int fd=open("/tmp/cttyname", O_RDWR);
    read(fd, tty, 32);
    while (1)
    {
        if (access("/tmp/cttyflag", F_OK) < 0)
        {
           ;
        }
        else
        {
           stdio_redirect_daemon(tty);
        }
        sleep(1);
    }
    return 0; 
}
=============================================================== ======================================
ctty客户端
int main()
{
    char *tty=ttyname(1);
    char cmd[64] = {0};
    strcpy(cmd, "echo ");
    strcat(cmd, tty);
    strcat(cmd, " /tmp/cttyname");
    system(cmd);
    system("touch /tmp/cttyflag");
    while (1)
    {
        sleep(1);
    }
    return 0;
}

服务端需要嵌入到应用程序中。客户端单独编译后部署到设备中,当登陆到设备后,运行客户端,即可实时
查看到当前应用程序在标准终端的输出。

你可能感兴趣的:(嵌入式调试)