(4) 测试验证
a. 假设需要自动重启的程序为demo.c,其代码实现如下所示:
| /* * * demo * */ #include <stdio.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/wait.h> #include <stdlib.h> #include <time.h> #define LOG_FILE "/var/log/demo.log" void demo_log(int num) { time_t t; struct tm *tm; char *log_file; FILE *fp_log; char date[128]; log_file = LOG_FILE; fp_log = fopen(log_file, "a+"); if (NULL == fp_log) { fprintf(stderr, "Could not open logfile '%s' for writingn", log_file); } time(&t); tm = localtime(&t); strftime(date,127,"%Y-%m-%d %H:%M:%S",tm); /* write the message to stdout and/or logfile */ fprintf(fp_log, "[%s] num = %dn", date, num); fflush(fp_log); fclose(fp_log); } int main(int argc, char **argv[]) { int num = 0; while(1) { sleep(10); num++; demo_log(num); } } |
b. 测试准备和说明:
b1. 以上相关服务程序编译后的二进制文件为: supervisor 和 demo
b2. 执行如下测试命令 ./supervisor ./demo
c. 测试的结果:
c1. execv(progname, arg) 执行成功后,其后的代码不会执行;只有当执行错误时,才会返回 -1。原来调用execv进程的代码段会被progname应用程序的代码段替换。
c2. 当kill掉子进程时,父进程wait函数会接收到子进程退出的信号,进而循环再启动子进程,此过程实时性非常高。
c3. 当kill掉父进程时,子进程会被init进程接管,如果此时再kill掉子进程,则子进程会退出。
c4. 当同时kill掉父子进程,则父子进程都会退出。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易采站长站。








