#include "mgstat.h" static int cur_nr; struct status_t *new_status(char *s, int len) { struct status_t *t; int l = len; if(len > sizeof t->status - 1) l = sizeof t->status; t = calloc(1, sizeof *t); if(!t) errx(1, "Cannot allocate memory."); INIT_LIST_HEAD(&t->head); strncpy(t->status, s, l); list_add(&t->head, &status_l); return t; } /* * Return status number associated with status * description string. */ unsigned int find_status(char *s, int len) { struct list_head *h; struct status_t *t; list_for_each(h, &status_l) { t = list_entry(h, struct status_t, head); if(!strncmp(t->status, s, len)) return t->nr; } if(cur_nr >= MAX_STATUS_NR) { #ifdef DEBUG fprintf(stderr, "Max status codes reached.\n"); #endif return -1; } t = new_status(s, len); t->nr = cur_nr; cur_nr++; return t->nr; } char *find_by_nr(unsigned int nr) { struct list_head *h; struct status_t *t; list_for_each(h, &status_l) { t = list_entry(h, struct status_t, head); if(t->nr == nr) return t->status; } return 0; } /* * Write status information to a history file. */ void write_status(int fd) { struct list_head *h; struct status_t *t; if(write(fd, &cur_nr, sizeof(int)) < sizeof(int)) { fprintf(stderr, "Cannot write status code info.\n"); return; } list_for_each_r(h, &status_l) { t = list_entry(h, struct status_t, head); if(write(fd, t, sizeof *t) < sizeof *t) { fprintf(stderr, "Cannot write status code info.\n"); return; } } print_msg("Saving status codes history.\n"); } /* * Read "status_description -> number" mappings from a history file. */ void read_status(int fd) { int i; struct status_t t, *tmp; if(read(fd, &cur_nr, sizeof(int)) != sizeof(int)) { fprintf(stderr, "Cannot read status history\n"); return; } for(i = 0; i < cur_nr; i++) { if(read(fd, &t, sizeof t) < sizeof t) { fprintf(stderr, "Cannot read status history\n"); return; } #ifdef DEBUG printf(__FUNCTION__": %s %d\n", t.status, t.nr); #endif tmp = calloc(1, sizeof *tmp); if(!tmp) errx(1, "Cannot allocate memory"); memcpy(tmp, &t, sizeof t); list_add(&tmp->head, &status_l); } print_msg("Status code information loaded: %d entries ", cur_nr); if(cur_nr == MAX_STATUS_NR) print_msg("(max reached)\n"); print_msg("\n"); }