現在就來實踐一下,寫一個自動關機的小程序。該程序可以守護進程的方式運行,當用戶在一定時間(比如30分鐘)沒有鼠標和鍵盤操作後就會自動關機。
這個程序利用了上篇文章中實現的daemonize函數,為程序創建了守護進程所需要的運行環境。
由於需要同時監聽鼠標和鍵盤操作,所以需要采用多線程的方式來實現。其中兩個線程分別監視鼠標和鍵盤,一旦檢測到相應動作(鼠標點擊和移動、擊鍵等),全局時間戳stamp(time_t)就會被設成當前時間。主線程每隔一定時間(比如1秒)檢查stamp,若當前時間值(time(NULL))比stamp大30*60,則執行停機操作(使用system函數執行init 0命令,或者使用reboot函數)。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h> //~ O_RDWR, S_IRWXU etc.
#include <pthread.h>
#include <time.h>
#include <limits.h>
#include <signal.h>
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);
}
char buf[256];
while( read(fd, buf, sizeof(buf)) > 0 )
{
/*printf("Moused Moved.\n");*/
pthread_mutex_lock(&stamp_mutex);
//time(&stamp);
stamp = time(NULL);
pthread_mutex_unlock(&stamp_mutex);
}
close(fd);
}
void *
listen_kb(void * arg)
{
int fd = open("/dev/input/event3", O_RDONLY);
if(fd < 0)
{
perror("open event3");
exit(1);
}
char buf[256];
12下一頁