An overview of the

In the embedded Linux operating system, you can log in to the device remotely (Telnet or SSH) to view the debugging information printed in real time. In this case, you need to redirect the debugging information output to the serial port to the interface of the terminal you have logged in to.

You can also restart the program to the current terminal interface, but when the program has a problem, if you restart the program, it may destroy the problem site, and then find the problem is not easy to find.

The following is the implementation of the code, can output to the serial port log information, redirection to the current Telnet or SSH interface, is not magic!

The implementation code

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

int main(int argc, char *argv[])
{
    int tty = - 1;
    char *tty_name = NULL;

    if(argc < 2)
    {
        printf("miss argument\n");
        return 0;
    }

    /* Get the current tty name */
    tty_name = ttyname(STDOUT_FILENO);
    printf("tty_name: %s\n", tty_name);

    if(!strcmp(argv[1]."on"))
    {
        /* Redirects console to the current tty */
        tty = open(tty_name, O_RDONLY | O_WRONLY);
        ioctl(tty, TIOCCONS);
        perror("ioctl TIOCCONS");
    }
    else if(!strcmp(argv[1]."off"))
    {
        /* Restore console */
        tty = open("/dev/console", O_RDONLY | O_WRONLY);
        ioctl(tty, TIOCCONS);
        perror("ioctl TIOCCONS");
    }
    else
    {
        printf("error argument\n");
        return 0;
    }

    close(tty);
    return 0;
}
Copy the code

Compile operation

compile

gcc  log.c -o log 
Copy the code

run

. /log on       Redirect logs to the current terminal interface. /log off       Restore log output to debug serial port
Copy the code

Welcome to follow your personal wechat official account: