之前写的博文里已经实现了屏幕亮度的调节(http://jianshusoft.blog.51cto.com/2380869/810780),但是毕竟没有和Fn快捷键绑定,略有遗憾。所以写个小程序让键盘来控制亮度。原理很简单,监控acpi_video0目录下的brightness文件,如果有改动,则修改到intel_backlight下的brightness。而且把密码隐藏在了程序里,不用担心shell脚本会漏露密码了。

 
  
  1. #include <stdlib.h> 
  2. #include <unistd.h> 
  3.  
  4.  
  5. int main() 
  6.     int fd = inotify_init(); 
  7.     if(fd == -1){ 
  8.         printf("inotify_init error!\n"); 
  9.         exit(-1); 
  10.     } 
  11.  
  12.     system("echo \"这里输入密码\" | sudo -S chmod 777 /sys/class/backlight/intel_backlight/brightness"); 
  13.  
  14.     inotify_add_watch(fd, "/sys/class/backlight/acpi_video0/brightness", IN_MODIFY); 
  15.  
  16.     inotify_event buf[1]; 
  17.     int size = sizeof(inotify_event) * 1; 
  18.  
  19.     int last = 0; 
  20.     char brightness[10]; 
  21.     while(read(fd, buf, size)){ 
  22.         FILE *source = fopen("/sys/class/backlight/acpi_video0/brightness""r"); 
  23.         if(fgets(brightness, 10, source) != NULL){ 
  24.             fclose(source); 
  25.  
  26.             int temp = (atoi(brightness) + 1) * 4882 / 10; 
  27.             if(last != temp ){ 
  28.                 last = temp; 
  29.                 sprintf(brightness, "%d", temp); 
  30.                 FILE *file = fopen("/sys/class/backlight/intel_backlight/brightness""w"); 
  31.                 fputs(brightness, file); 
  32.                 fclose(file); 
  33.  
  34.                 printf("changed %s \n", brightness); 
  35.             } 
  36.  
  37.             //每次按键会修改三次,所以忽略后两次 
  38.             //read(fd, buf, size); 
  39.             //read(fd, buf, size); 
  40.         } 
  41.  
  42.     } 
  43.  
  44.     int result = close(fd); 
  45.     printf("%d", result);