用户名  找回密码
 FreeOZ用户注册
查看: 1336|回复: 1
打印 上一主题 下一主题

[Linux] 一个简单的程序timeout控制器

[复制链接]
跳转到指定楼层
1#
发表于 26-5-2009 10:10:06 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有帐号?FreeOZ用户注册

x
很简单,不过比较实用,用来妨止程序失去控制。以分钟为单位
涉及问题:
1. linux下c++/c编程
2. 多进程控制
3. 简单信号处理
  1. #include <iostream>

  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <stdint.h>

  5. #include <sys/types.h>
  6. #include <sys/time.h>
  7. #include <time.h>

  8. #include <string.h>
  9. #include <errno.h>
  10. #include <signal.h>

  11. using std::cout;
  12. using std::cerr;
  13. using std::endl;

  14. static void usage(const char * prog)
  15. {
  16.   cerr << "Usage : " << prog << " <minutes> <prog> <arg1> <arg2...>" << endl;
  17. }

  18. static void child_return(int sig)
  19. {
  20.   cerr << "Child return, parent exits." << endl;
  21.   exit(0);
  22. }

  23. int main(int argc, char ** argv)
  24. {
  25.   const char * prog = argv[0];

  26.   if(argc<3)
  27.   {
  28.     usage(prog);
  29.     exit(-1);
  30.   }

  31.   const char * min_str = argv[1];
  32.   int timeout_min = atoi(min_str);

  33.   if(min_str <= 0)
  34.   {
  35.     cerr << "Error : minutes should be positive." << endl << endl;
  36.     usage(prog);
  37.     exit(-2);
  38.   }

  39.   time_t begin_time = time(NULL);
  40.   pid_t child_pid = -1;

  41.   child_pid = fork();

  42.   if(child_pid == 0) //child
  43.   {
  44.     char * child_args[argc - 2 + 1];
  45.     int k;

  46.     bzero(child_args, sizeof(child_args));

  47.     for(k=0; k < argc - 2 + 1; ++k)
  48.     {
  49.       child_args[k] = argv[k+2];
  50.       cout << "DEBUG " << child_args[k] << endl;
  51.     }

  52.     execvp(child_args[0], child_args);

  53.     exit(-1);
  54.   }
  55.   else if(child_pid < 0) //fork fails
  56.   {
  57.     cerr << "fork() error: " << strerror(errno) << endl;
  58.     exit(-3);
  59.   }

  60.   //parent
  61.   
  62.   signal(SIGCHLD, child_return);

  63.   while(1)
  64.   {
  65.     time_t cur = time(NULL);
  66.     if(cur - begin_time < (timeout_min * 60))
  67.     {
  68.       cout << "DEBUG p " << timeout_min * 60 - cur + begin_time << endl;
  69.       sleep(timeout_min * 60 - cur + begin_time);
  70.     }
  71.     else
  72.       break;
  73.   }

  74.   kill(child_pid, SIGKILL);

  75.   cerr << "Kill child process." << endl;

  76.   return 0;
  77. }
复制代码
回复  

举报

2#
发表于 26-5-2009 12:05:53 | 只看该作者
哈哈,就是单片机的看门狗机制。
回复  

举报

您需要登录后才可以回帖 登录 | FreeOZ用户注册

本版积分规则

小黑屋|手机版|Archiver|FreeOZ论坛

GMT+10, 26-4-2025 01:02 , Processed in 0.012455 second(s), 17 queries , Gzip On, Redis On.

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表