转自 http://blog.csdn.net/cinmyheart/article/details/38960967
关于 "setconsole.c" Alesssandro Rubini 的邮件回复
抱着试一试的心态给偶像写了一封求助e-mail,回复了!!!我的小心脏啊~
呵呵~Rubini是谁不解释了...
我的HELP原文主要的关于setconsole.c的问题,这个是LDD3的一个小程序
setconsole.c
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <errno.h>
- #include <unistd.h>
- #include <sys/ioctl.h>
-
- int main(int argc, char **argv)
- {
- char bytes[2] = {11,0};
-
- if (argc==2) bytes[1] = atoi(argv[1]);
- else {
- fprintf(stderr, "%s: need a single arg\n",argv[0]); exit(1);
- }
- if (ioctl(STDIN_FILENO, TIOCLINUX, bytes)<0) {
- fprintf(stderr,"%s: ioctl(stdin, TIOCLINUX): %s\n",
- argv[0], strerror(errno));
- exit(1);
- }
- exit(0);
- }
但是在虚拟控制台之间测试一直不成功,很纠结~
我用*某*搜索引擎检索了很多blog,都是水...都是直接copy原书的内容,仅发现一个有对程序进行测试的,但是测试没有成功,google不能用,不知道情况如果,用TTT检索出来的一样,没有实质性的对setconsole.c的讨论和测试!
下面是Rubini 对我的回复:


首先指出了我的误区
1. ioctl(TIOCLINUX) 影响的并不是printf,而是printk!
2.tty 或者 terminal 不是console! 通过ctrl + alt + F* (1~6 )达到的都是控制台,F7是图形环境,不是console!
Allan Cruse 在2007年对setconsole做了一点改进
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #include <fcntl.h> // for open() <--- added
- #include <stdio.h> // for fprintf()
- #include <errno.h> // for errno
- #include <stdlib.h> // for exit()
- #include <unistd.h> // for STDIN_FILENO
- #include <string.h> // for strerror()
- #include <sys/ioctl.h> // for ioctl()
- #include <asm/ioctls.h> // for TIOCLINUX
-
- int main( int argc, char **argv )
- {
- char bytes[ 2 ] = { 11, 0 };
-
- if ( argc == 2 ) bytes[1] = atoi( argv[1] );
- else {
- fprintf( stderr, "%s: need a single argument\n", argv[0] );
- exit(1);
- }
-
- int fd = open( "/dev/console", O_RDWR );
- if ( fd < 0 ) { perror( "/dev/console" ); exit(1); }
-
- if ( ioctl( fd, TIOCLINUX, bytes ) < 0 )
- {
- fprintf( stderr, "%s: ioctl( fd, TIOCLINUX ): %s\n",
- argv[0], strerror( errno ) );
- exit(1);
- }
-
- exit(0);
- }
是可以在console之间重定向IO的!!

这幅图看到的是tty4,我把控制台的IO重定向到了console 3,也就是/dev/tty3
切换到tty2,我们插入hello.ko 模块,调用printk,打印hello world
我故意执行了tty这个shell程序,提示读者当前我们在tty2,进行insmod操作

明明是有hello world的为什么不打印呢?去哪儿了?console 3!
我们ctrl + alt + F3 切换到console 3看看

终于搞定了!利用ioctl实现了对于不同console之间的IO重定向!
最后谢谢偶像~ Alesssandro Rubini & Allan Cruse
