编辑
2024-12-17
工作知识
0
请注意,本文编写于 171 天前,最后修改于 171 天前,其中某些信息可能已经过时。

在看LDD3时发现可以通过TIOCLINUX的ioctl控制内核日志输出。其代码可以如下:

#include <stdio.h> #include <fcntl.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> #include <sys/ioctl.h> #include <string.h> int main( int argc, char **argv ) { char bytes[ 2 ] = { 11, 0 }; // 11 is the TIOCLINUX command-number if ( argc == 2 ) bytes[1] = atoi( argv[1] ); // console id-number else { fprintf( stderr, "%s: need a single argument\n", argv[0] ); exit(1); } int fd = open( "/dev/console", O_RDWR ); // <--- added if ( fd < 0 ) { perror( "/dev/console" ); exit(1); } // <--- added if ( ioctl( fd, TIOCLINUX, bytes ) < 0 ) // <--- changed { fprintf( stderr, "%s: ioctl( fd, TIOCLINUX ): %s\n", // <--- argv[0], strerror( errno ) ); exit(1); } exit(0); }

通过gcc编译

gcc setconsole.c -o setconsole 查看系统默认console上绑定的tty

cat /sys/devices/virtual/tty/console/active tty0

如果内核日志需要定向到其他tty上,可以如下运行

让内核日志在只在tty3上出现

./setconsole 3 # tty3上会出现内核日志,其他tty不会有内核日志 让内核日志在所有的tty上出现

./setconsole 0 # 所有可关联的tty都会出现内核日志