Linux虛擬終端控制小鍵盤燈
Linux核心提供函式 ioctl 用於控制底層裝置與描述符。引數KDSETLED指示小鍵盤燈的狀態,0x01為scroll lock燈亮,0x02為num lock燈亮, 0x04為caps lock燈亮。
}
return 0;
|
編譯:gcc test.c -o test
root使用者執行, 指示燈依次閃亮,最後scroll lock燈亮。
我有一個例子是讓三個燈不斷的在閃的
例子如下:
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
#include <sys/stat.h>
#include <linux/kd.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#define ERROR -1
int fd; /* File descriptor for console (/dev/tty/) */
void sighandler(int signum);
void main()
{
int i;
/* To be used as the fd in ioctl(). */
if ((fd = open("/dev/console", O_NOCTTY)) == ERROR)
{
perror("open");
exit(ERROR);
}
signal(SIGINT, sighandler);
signal(SIGTERM, sighandler);
signal(SIGQUIT, sighandler);
signal(SIGTSTP, sighandler);
printf("w00w00!\n\n");
printf("To exit hit Control-C.\n");
while (1)
{
for (i = 0x01; i <= 0x04; i++)
{
/* We do this because there is no LED for 0x03. */
if (i == 0x03) continue;
usleep(50000);
if ((ioctl(fd, KDSETLED, i)) == ERROR) {
perror("ioctl");
close(fd);
exit(ERROR);
}
}
}
close(fd);
}
void sighandler(int signum)
{
/* Turn off all leds. No LED == 0x0. */
if ((ioctl(fd, KDSETLED, 0x0)) == ERROR)
{
perror("ioctl");
close(fd);
exit(ERROR);
}
printf("\nw00w00!\n");
close(fd);
exit(0);
}
///////////////
#define KDGETLED 0x4B31 /* return current led state */
#define KDSETLED 0x4B32 /* set led state [lights, not flags] */
#define LED_SCR 0x01 /* scroll lock led */
#define LED_NUM 0x02 /* num lock led */
#define LED_CAP 0x04 /* caps lock led */
每次切換前,記錄當前scroll 、num 和caps 狀態,即是否開啟,然後 ioctl(fd, KDSETLED, 0x0)) 關閉所有LED, 然後點亮當前需要的key,其它的key根據上次狀態恢復即可
//////////////////////////////////////