From 94bbf631408b0217f8682da8b83b18701538e01e Mon Sep 17 00:00:00 2001 From: Sami Kerola Date: Sat, 22 Oct 2011 18:05:42 +0200 Subject: [PATCH] libproc-ng: add strtosig() function The function will convert a signal number string to a signal name, or vice a verse. Return value is string, which is an function user is expected to free after use. Signed-off-by: Sami Kerola --- proc/sig.c | 43 +++++++++++++++++++++++++++++++++++++++++++ proc/sig.h | 2 ++ 2 files changed, 45 insertions(+) diff --git a/proc/sig.c b/proc/sig.c index 3d6e0584..1137fefa 100644 --- a/proc/sig.c +++ b/proc/sig.c @@ -209,6 +209,49 @@ end: return ret; } +/* strtosig is similar to print_given_signals() with exception, that + * this function takes a string, and converts it to a signal name or + * a number string depending on which way a round conversion is + * queried. Non-existing signals return NULL. Notice that the + * returned string should be freed after use. + */ +char *strtosig(const char *restrict s){ + char *converted = NULL, *copy, *p, *endp; + int i, numsignal = 0; + + copy = strdup(s); + if (!copy) + err(EXIT_FAILURE, "cannot duplicate string"); + for (p = copy; *p != '\0'; p++) + *p = toupper(*p); + p = copy; + if (p[0] == 'S' && p[1] == 'I' && p[2] == 'G') + p += 3; + if (isdigit(*p)){ + numsignal = strtol(s,&endp,10); + if(*endp || endp==s) return NULL; /* not valid */ + } + if (numsignal){ + for (i = 0; i < number_of_signals; i++){ + if (numsignal == sigtable[i].num){ + converted = strdup(sigtable[i].name); + break; + } + } + } else { + for (i = 0; i < number_of_signals; i++){ + if (strcmp(p, sigtable[i].name) == 0){ + converted = malloc(sizeof(char) * 8); + if (converted) + snprintf(converted, sizeof(converted) - 1, "%d", sigtable[i].num); + break; + } + } + } + free(p); + return converted; +} + void pretty_print_signals(void){ int i = 0; while(++i <= number_of_signals){ diff --git a/proc/sig.h b/proc/sig.h index ee850a2a..0c842ab7 100644 --- a/proc/sig.h +++ b/proc/sig.h @@ -22,6 +22,8 @@ extern const char *signal_number_to_name(int signo); extern int print_given_signals(int argc, const char *restrict const *restrict argv, int max_line); +extern char *strtosig(const char *restrict s); + extern void pretty_print_signals(void); extern void unix_print_signals(void);