linux有什么特点,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);  }。

全部

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值