From 260f167818f960d9385d88784ab4bd3a00a531fb Mon Sep 17 00:00:00 2001 From: Martin Mares Date: Fri, 31 Dec 2010 17:18:37 +0100 Subject: [PATCH] nwho: Output is now sorted as specified by command-line options --- nwho.c | 92 ++++++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 83 insertions(+), 9 deletions(-) diff --git a/nwho.c b/nwho.c index b7c932c..7e89b65 100644 --- a/nwho.c +++ b/nwho.c @@ -12,10 +12,10 @@ #include #include #include +#include #include "nwho.h" -static int is_uptime; static time_t now; struct out_host { @@ -80,6 +80,43 @@ new_user(struct out_host *host, struct userinfo *ui) }; } +static int +cmp_users_by_hosts(const void *va, const void *vb) +{ + const struct out_user *a = va; + const struct out_user *b = vb; + return strcmp(a->host->name, b->host->name); +} + +static int +cmp_users_by_names(const void *va, const void *vb) +{ + const struct out_user *a = va; + const struct out_user *b = vb; + return strcmp(a->user->name, b->user->name); +} + +static void +sort_users(int by_hosts) +{ + qsort(user_array, num_users, sizeof(user_array[0]), + (by_hosts ? cmp_users_by_hosts : cmp_users_by_names)); +} + +static int +cmp_hosts(const void *va, const void *vb) +{ + const struct out_host * const *a = va; + const struct out_host * const *b = vb; + return strcmp((*a)->name, (*b)->name); +} + +static void +sort_hosts(void) +{ + qsort(host_array, num_hosts, sizeof(host_array[0]), cmp_hosts); +} + static void puttime(int s) { @@ -202,6 +239,20 @@ scan(void) closedir(d); } +static void +usage(void) +{ + printf("\ +Usage: nwho \n\ + or: nuptime \n\ +\n\ +Options:\n\ +-h Sort user list by hosts (default: by users)\n\ +-u Display host uptimes (default if called as `nuptime')\n\ +"); + exit(0); +} + int main(int argc, char **argv) { @@ -210,13 +261,30 @@ main(int argc, char **argv) printf("nwho " STRINGIFY(VERSION) "\n"); return 0; } + if (argc == 2 && !strcmp(argv[1], "--help")) + usage(); + + int opt; + int uptime_mode = !!strstr(argv[0], "uptime"); + int want_sort_by_hosts = 0; - if (strstr(argv[0], "uptime")) - is_uptime = 1; - if (argc != 1) + while ((opt = getopt(argc, argv, "hu")) >= 0) + switch (opt) + { + case 'h': + want_sort_by_hosts = 1; + break; + case 'u': + uptime_mode = 1; + break; + default: + fprintf(stderr, "Try `%s --help' for more information.\n", argv[0]); + exit(1); + } + if (optind < argc) { - fprintf(stderr, "Usage: %s\n", argv[0]); - return 1; + fprintf(stderr, "This program does not need any arguments. Try `%s --help' for more information.\n", argv[0]); + exit(1); } now = time(NULL); @@ -227,9 +295,15 @@ main(int argc, char **argv) return 0; } - if (!is_uptime) - show_users(); + if (!uptime_mode) + { + sort_users(want_sort_by_hosts); + show_users(); + } else - show_uptime(); + { + sort_hosts(); + show_uptime(); + } return 0; } -- 2.39.2