linux没有几分钟就自动关机,Linux中实现30分钟无操作自动关机

#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);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值