现在就来实践一下,写一个自动关机的小程序。该程序可以守护进程的方式运行,当用户在一定时间(比如30分钟)没有鼠标和键盘操作后就会自动关机。 这个程序利用了上篇文章中实现的daemonize函数,为程序创建了守护进程所需要的运行环境。 由于需要同时监听鼠标和键盘操作,所以需要采用多线程的方式来实现。
其中两个线程分别监视鼠标和键盘,一旦检测到相应动作(鼠标点击和移动、击键等),全局时间戳stamp(time_t)就会被设成当前时间。主线程每隔一定时间(比如1秒)检查stamp,若当前时间值(time(NULL))比stamp大30*60,则执行停机操作(使用system函数执行init 0命令,或者使用reboot函数)。
#include #include #include #include #include //~ O_RDWR, S_IRWXU etc。 #include
#include #include #include void daemonize(); //~ thread functions void *listen_ms(void *); void *listen_kb(void *); //~ time stamp, keeping the time //~ when the last KB or Mouse event happened。
volatile time_t stamp; //~ mutex keeping stamp consistent。 pthread_mutex_t stamp_mutex; int main() { daemonize(); //~ initialize the mutex, stamp pthread_mutex_init(&stamp_mutex, NULL); //time(&stamp); stamp = time(NULL); //~ create two threads monitoring the Mouse and Keyboard。
pthread_t ms_tid, kb_tid; if(pthread_create(&ms_tid, NULL, listen_ms, NULL) != 0) { perror("pthread_create"); exit(1); } if(pthread_create(&kb_tid, NULL, listen_kb, NULL) != 0) { perror("pthread_create"); exit(1); } unsigned int interval = 60 * 30; while(1) { sleep(1); pthread_mutex_lock(&stamp_mutex); if( time(NULL) - stamp > interval ) { /*printf("shutdown\n");*/ /*fflush(stdin);*/ system("init 0"); } pthread_mutex_unlock(&stamp_mutex); } //~ join the threads, though it'll never be excuted。
pthread_join(ms_tid, NULL); pthread_join(kb_tid, NULL); return 0; } void * listen_ms(void * arg) { int fd = open("/dev/input/mice", O_RDONLY); if(fd < 0) { perror("open mice"); exit(1); }。
全部