-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.c
94 lines (76 loc) · 1.32 KB
/
util.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/** \file util.c
* Provides some useful utility functions
*
* Dov Salomon (dms833)
*/
#include <errno.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "util.h"
extern char *argv0;
/* prints message and exit */
void die(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
fprintf(stderr, "%s: ", argv0);
vfprintf(stderr, fmt, ap);
va_end(ap);
if (fmt[0] && fmt[strlen(fmt)-1] != ':') {
fputc('\n', stderr);
} else {
fputc(' ', stderr);
perror(NULL);
}
exit(1);
}
/* malloc with error checking */
void *xmalloc(size_t n)
{
void *p;
if (!(p = malloc(n)))
die("malloc():");
return p;
}
/* gets a nul-terminated line from fd */
int read_line(int fd, char *buf, size_t bfsz)
{
int n;
int i = 0;
char c = '\0';
do {
n = read(fd, &c, sizeof(char));
if (n == -1)
if (errno == EINTR)
continue;
else
return -1;
else if (n == 0)
if (i)
break;
else
return 0;
else
buf[i++] = c;
} while (c != '\n' && i < bfsz);
buf[i-1] = '\0';
return i;
}
/* converts port number to ushort
*
* returns zero on error
* (we won't use port "0")
*/
unsigned short atoport(const char *str)
{
char *end;
unsigned long int port;
port = strtoul(str, &end, 10);
// not a valid string
if (*end != '\0')
return 0;
return port;
}