pb-event: move send code to a separate function
authorJeremy Kerr <jk@ozlabs.org>
Mon, 6 May 2013 06:23:17 +0000 (14:23 +0800)
committerJeremy Kerr <jk@ozlabs.org>
Thu, 9 May 2013 00:47:54 +0000 (08:47 +0800)
Signed-off-by: Jeremy Kerr <jk@ozlabs.org>
utils/pb-event.c

index 3649c9fc83a4e6840c4ba398df1a0f57e7094ccb..4a167192c7a99c34a172b7a9240e8b1dfbd9d37e 100644 (file)
@@ -22,6 +22,7 @@
 
 #define _GNU_SOURCE
 #include <assert.h>
+#include <err.h>
 #include <errno.h>
 #include <stdio.h>
 #include <stdlib.h>
@@ -121,26 +122,50 @@ static ssize_t parse_event_file(FILE *filp, char *buf, size_t max_len)
        return len;
 }
 
-int main(int argc, char *argv[])
+static int send_event(char *buf, ssize_t len)
 {
        struct sockaddr_un addr;
+       int sd, i;
+
+       sd = socket(PF_UNIX, SOCK_DGRAM, 0);
+       if (sd < 0)
+               err(EXIT_FAILURE, "socket");
+
+       memset(&addr, 0, sizeof(addr));
+       addr.sun_family = AF_UNIX;
+       strcpy(addr.sun_path, PBOOT_USER_EVENT_SOCKET);
+
+       for (i = 10; i; i--) {
+               ssize_t sent = sendto(sd, buf, len, 0,
+                               (struct sockaddr *)&addr, SUN_LEN(&addr));
+
+               if (sent == len)
+                       break;
+
+               DBG("pb-event: waiting for server %d\n", i);
+               sleep(1);
+       }
+
+       close(sd);
+
+       if (!i)
+               err(EXIT_FAILURE, "send");
+
+       DBG("pb-event: wrote %zu bytes\n", len);
+
+       return 0;
+}
+
+int main(int argc, char *argv[])
+{
        char buf[PBOOT_USER_EVENT_SIZE];
        ssize_t len;
-       int s;
-       int i;
 
        if (argc >= 2 && !strcmp(argv[1], "-h")) {
                print_usage();
                return EXIT_SUCCESS;
        }
 
-       s = socket(PF_UNIX, SOCK_DGRAM, 0);
-
-       if (s < 0) {
-               fprintf(stderr, "pb-event: socket: %s\n", strerror(errno));
-               return EXIT_FAILURE;
-       }
-
        if (argc > 1) {
                len = parse_event_args(argc - 1, argv + 1,
                                        buf, sizeof(buf));
@@ -151,26 +176,7 @@ int main(int argc, char *argv[])
        if (len < 0)
                return EXIT_FAILURE;
 
-       memset(&addr, 0, sizeof(addr));
-       addr.sun_family = AF_UNIX;
-       strcpy(addr.sun_path, PBOOT_USER_EVENT_SOCKET);
-
-       for (i = 10; i; i--) {
-               ssize_t sent = sendto(s, buf, len, 0, (struct sockaddr *)&addr,
-                       SUN_LEN(&addr));
-
-               if (sent == len)
-                       break;
-
-               DBG("pb-event: waiting for server %d\n", i);
-               sleep(1);
-       }
-
-       if (!i) {
-               fprintf(stderr, "pb-event: send: %s\n", strerror(errno));
-               return EXIT_FAILURE;
-       }
+       send_event(buf, len);
 
-       DBG("pb-event: wrote %u bytes\n", (unsigned int)len);
        return EXIT_SUCCESS;
 }