一个简单的程序timeout控制器
很简单,不过比较实用,用来妨止程序失去控制。以分钟为单位涉及问题:
1. linux下c++/c编程
2. 多进程控制
3. 简单信号处理#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>
#include <sys/types.h>
#include <sys/time.h>
#include <time.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
using std::cout;
using std::cerr;
using std::endl;
static void usage(const char * prog)
{
cerr << "Usage : " << prog << " <minutes> <prog> <arg1> <arg2...>" << endl;
}
static void child_return(int sig)
{
cerr << "Child return, parent exits." << endl;
exit(0);
}
int main(int argc, char ** argv)
{
const char * prog = argv;
if(argc<3)
{
usage(prog);
exit(-1);
}
const char * min_str = argv;
int timeout_min = atoi(min_str);
if(min_str <= 0)
{
cerr << "Error : minutes should be positive." << endl << endl;
usage(prog);
exit(-2);
}
time_t begin_time = time(NULL);
pid_t child_pid = -1;
child_pid = fork();
if(child_pid == 0) //child
{
char * child_args;
int k;
bzero(child_args, sizeof(child_args));
for(k=0; k < argc - 2 + 1; ++k)
{
child_args = argv;
cout << "DEBUG " << child_args << endl;
}
execvp(child_args, child_args);
exit(-1);
}
else if(child_pid < 0) //fork fails
{
cerr << "fork() error: " << strerror(errno) << endl;
exit(-3);
}
//parent
signal(SIGCHLD, child_return);
while(1)
{
time_t cur = time(NULL);
if(cur - begin_time < (timeout_min * 60))
{
cout << "DEBUG p " << timeout_min * 60 - cur + begin_time << endl;
sleep(timeout_min * 60 - cur + begin_time);
}
else
break;
}
kill(child_pid, SIGKILL);
cerr << "Kill child process." << endl;
return 0;
} 哈哈,就是单片机的看门狗机制。
页:
[1]