Linux内核提供函数 ioctl 用于控制底层设备与描述符。参数KDSETLED指示小键盘灯的状态,0x01为scroll lock灯亮,0x02为num lock灯亮, 0x04为caps lock灯亮。
|
编译: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根据上次状态恢复即可
//