General update
[transsip.git] / src / xutils.c
blob3caecd527c3f87c0939b4c8c899765e45852e65b
1 #define _BSD_SOURCE
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <unistd.h>
5 #include <string.h>
6 #include <errno.h>
7 #include <fcntl.h>
8 #include <signal.h>
9 #include <stdarg.h>
10 #include <sys/types.h>
11 #include <sys/stat.h>
12 #include <sys/types.h>
13 #include <sys/ioctl.h>
14 #include <sys/socket.h>
16 #include "xutils.h"
17 #include "xmalloc.h"
18 #include "die.h"
20 int open_or_die(const char *file, int flags)
22 int ret = open(file, flags);
23 if (ret < 0)
24 panic("Open error!!\n");
25 return ret;
28 int open_or_die_m(const char *file, int flags, mode_t mode)
30 int ret = open(file, flags, mode);
31 if (ret < 0)
32 panic("Open error!!\n");
33 return ret;
36 ssize_t read_or_die(int fd, void *buf, size_t len)
38 ssize_t ret = read(fd, buf, len);
39 if (ret < 0) {
40 if (errno == EPIPE)
41 exit(EXIT_SUCCESS);
42 panic("Read error!!\n");
45 return ret;
48 ssize_t write_or_die(int fd, const void *buf, size_t len)
50 ssize_t ret = write(fd, buf, len);
51 if (ret < 0) {
52 if (errno == EPIPE)
53 exit(EXIT_SUCCESS);
54 panic("Write error!!\n");
57 return ret;
60 size_t strlcpy(char *dest, const char *src, size_t size)
62 size_t ret = strlen(src);
63 if (size) {
64 size_t len = (ret >= size) ? size - 1 : ret;
65 memcpy(dest, src, len);
66 dest[len] = '\0';
68 return ret;
71 int slprintf(char *dst, size_t size, const char *fmt, ...)
73 int ret;
74 va_list ap;
75 va_start(ap, fmt);
76 ret = vsnprintf(dst, size, fmt, ap);
77 dst[size - 1] = '\0';
78 va_end(ap);
79 return ret;
82 char **strntoargv(char *str, size_t len, int *argc)
84 int done = 0;
85 char **argv = NULL;
87 if (argc == NULL)
88 panic("argc is null!\n");
89 *argc = 0;
90 if (len <= 1) /* '\0' */
91 goto out;
92 while (!done) {
93 while (len > 0 && *str == ' ') {
94 len--;
95 str++;
97 if (len > 0 && *str != '\0') {
98 (*argc)++;
99 argv = xrealloc(argv, 1, sizeof(char *) * (*argc));
100 argv[(*argc) - 1] = str;
101 while (len > 0 && *str != ' ') {
102 len--;
103 str++;
105 if (len > 0 && *str == ' ') {
106 len--;
107 *str = '\0';
108 str++;
110 } else {
111 done = 1;
114 out:
115 return argv;