in scripts/hypervisor.c [159:260]
int main(int argc, char *argv[])
{
int ssec = INTERVAL, ret, status;
int first_start = 1;
int pipefd[2], waited, alive, isdaemon;
char buf[1024], info[4096];
pid_t pid;
time_t now, last = time(NULL);
if((ret = parseopt(argc, argv)) < 0 )
exit(ret);
daemonize ? go_daemon() : 0;
while(1){
if(pipe(pipefd) < 0){
fprintf(stderr, "- make pipe error : %s\n", strerror(errno));
exit(-1);
}
if( (ret = set_nonblock(pipefd[0])) < 0 ){
fprintf(stderr, "- set read nonblock error : %s\n", strerror(errno));
exit(-1);
}
if((pid = fork()) < 0){
fprintf(stderr, "- call fork() error : %s\n", strerror(errno));
exit(-1);
} else if (pid > 0){
close(pipefd[1]);
alive = waited = 1;
isdaemon = 0;
while(alive){
if(waited){
if(pid != waitpid(pid, &status, 0)){
sleep(INTERVAL);
continue;
} else {
fprintf(stderr, "- child process[%d] terminated .\n",pid);
if (first_start && (time(NULL)-last)<=5) {
fprintf(stderr,"- child process killed in %ld seconds , may wrong ! exit !\n",(time(NULL)-last));
exit(-1);
} else
first_start = 0;
waited = 0;
}
}
ret = read(pipefd[0], buf, sizeof(buf));
if(ret < 0){
if(errno == EAGAIN){
if(isdaemon == 0){
fprintf(stderr, "- this daemon process has no output !.\n");
isdaemon = 1;
}
sleep(INTERVAL);
continue;
} else {
fprintf(stderr, "- read pipe error : %s\n", strerror(errno));
exit(-1);
}
} else if(ret == 0) {
alive = 0;
close(pipefd[0]);
fprintf(stderr, "- read zero from pipe of children.\n");
if(isdaemon == 0){
getstatus(info, sizeof(info), status);
fprintf(stderr, "- extra info: %s\n", info);
} else {
strcpy(info, "");
}
continue;
} else {
fprintf(stderr, " - read pipe return: %d bytes\n", ret);
exit(-1);
}
}
fprintf(stderr, "- process: \"%s\" exit, restart it\n", cmd);
sleep(ssec);
now = time(NULL);
if(now - last > 3600){
ssec = INTERVAL;
last = now;
} else {
ssec = (ssec << 1) < MAXINTERVAL ? (ssec << 1) : MAXINTERVAL;
}
} else {
close(pipefd[0]);
fprintf(stderr, "- execute: \"%s\"\n", cmd);
if(execvp(cmd, cmdopt) < 0){
fprintf(stderr, "- execute: \"%s\" error, %s\n", cmd, strerror(errno));
exit(-1);
}
}
}
return 0;
}