Linux中实现30分钟无操作自动关机[Linux安全]
本文“Linux中实现30分钟无操作自动关机[Linux安全]”是由七道奇为您精心收集,来源于网络转载,文章版权归文章作者所有,本站不对其观点以及内容做任何评价,请读者自行判断,以下是其具体内容:
目前就来实践一下,写一个自动关机的小程序.该程序可以保护进程的方法运行,当用户在一按时间(比方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);
}
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];
while( read(fd, buf, sizeof(buf)) >0 )
{
/*printf("Key Hit.\n");*/
pthread_mutex_lock(&stamp_mutex);
//time(&stamp);
stamp = time(NULL);
pthread_mutex_unlock(&stamp_mutex);
}
close(fd);
}
void
daemonize()
{
if( fork() >0)
exit(0);
setsid();
close(0);
close(1);
close(2);
int fd = open("/dev/null", O_RDWR);
//int fd = open("log.txt", O_RDWR);
dup2(fd, 1);
dup2(fd, 2);
chdir("/");
umask(0);
signal(SIGCHLD, SIG_IGN);
}
需求阐明的是,同享变量stamp需求互斥地拜候.别的,对鼠标事件的监听是借助于对设备文件/dev/input/mice的读取(阻塞方法),键盘的监听借助于对/dev/input/event3的非阻塞读取,但我猜想在差别机械上大概会是别的诸如event0,event5之类的文件.
不足之处在于,无法对全屏情势举行判断,便是说,假如你全屏看一部较长的片子,大概会被关机……
以上是“Linux中实现30分钟无操作自动关机[Linux安全]”的内容,如果你对以上该文章内容感兴趣,你可以看看七道奇为您推荐以下文章:
本文地址: | 与您的QQ/BBS好友分享! |