hosts' list are now defined via config file

This commit is contained in:
Sergey Popov 2011-11-25 17:04:49 +04:00
parent 748bd4d10a
commit c93b612597
2 changed files with 46 additions and 16 deletions

View File

@ -1,4 +1,5 @@
INCLUDES=${gammu_CFLAGS}
yasnd_LDADD = ${libconfuse_LIBS}
bin_PROGRAMS = yasnd
yasnd_SOURCES = yasnd.c

61
yasnd.c
View File

@ -24,17 +24,7 @@ typedef struct {
int fail_count; // how many times in a row host was unreachable
} host_decl;
host_decl hosts[NUM_HOSTS];
void init()
{
hosts[0].hostname="10.0.0.1";
hosts[0].fail_count=0;
hosts[1].hostname="10.0.0.2";
hosts[1].fail_count=0;
hosts[2].hostname="10.0.0.254";
hosts[2].fail_count=0;
}
host_decl* hosts=NULL;
void log_event(const char *message)
{
@ -43,30 +33,66 @@ void log_event(const char *message)
#endif
}
void check_host(int num,host_decl host)
void* allocate_memory(int bytes)
{
void* result=malloc(bytes);
if (result==NULL)
{
log_event("Error: malloc failed");
exit(EXIT_FAILURE);
}
}
void init()
{
// Initialize config parsing library
cfg_opt_t opts[] = {
CFG_STR_LIST("hosts", "{}", CFGF_NONE),
CFG_END()
};
cfg_t *cfg;
cfg = cfg_init(opts, CFGF_NONE);
// check if config file is valid and parse it
if (cfg_parse(cfg, "/etc/yasnd.conf") == CFG_PARSE_ERROR)
{
log_event("error parsing config file");
exit(EXIT_FAILURE);
}
// allocate memory for hosts array...
hosts=allocate_memory(cfg_size(cfg,"hosts")*sizeof(host_decl));
// ...and fill it with config file content
for (int i=0;i<cfg_size(cfg,"hosts");i++)
{
hosts[i].hostname=cfg_getnstr(cfg,"hosts",i);
hosts[i].fail_count=0;
}
}
void check_host(int num,host_decl* host)
{
pid_t pid = fork();
if (pid < 0) {
log_event("can not fork child :(");
exit(EXIT_FAILURE);
}
// If pid == 0, then we are in the child
if (pid == 0) {
char tmp[50];
sprintf(tmp, "Pinging host %s", host.hostname);
sprintf(tmp, "Pinging host %s", host->hostname);
log_event(tmp);
execl("/bin/ping","/bin/ping","-c 4","-n",host.hostname,(char*) 0);
execl("/bin/ping","/bin/ping","-c 4","-n",host->hostname,(char*) 0);
// STUB: check result of exec call
exit(EXIT_SUCCESS);
}
// Save child's pid
host.helper_pid=pid;
host->helper_pid=pid;
}
void loop_function()
{
for (int i=0;i<NUM_HOSTS;i++)
{
check_host(i,hosts[i]);
check_host(i,&hosts[i]);
}
for (int i=0;i<NUM_HOSTS;i++)
{
@ -93,6 +119,9 @@ void loop_function()
void termination_handler(int signum)
{
closelog();
// free hosts structures memory
if (hosts!=NULL)
free(hosts);
exit(EXIT_SUCCESS);
}