root / mainbox / util.c @ ddd50354
History | View | Annotate | Download (2.17 KB)
1 |
#include "util.h" |
---|---|
2 |
#include "log.h" |
3 |
#include <stdlib.h> |
4 |
#include <stdio.h> |
5 |
#include <errno.h> |
6 |
#include <unistd.h> |
7 |
#include <sys/types.h> |
8 |
#include <sys/stat.h> |
9 |
#include <fcntl.h> |
10 |
|
11 |
/*
|
12 |
* read_file
|
13 |
*
|
14 |
* Reads in an entire file. Returns NULL on error, or a malloc'd pointer to a
|
15 |
* string which should later be freed.
|
16 |
*/
|
17 |
char *read_file(const char *filename) { |
18 |
int fd, len, size, nread;
|
19 |
char *str;
|
20 |
|
21 |
fd = open(filename, O_RDONLY); |
22 |
if (fd < 0) { |
23 |
log_perror(filename); |
24 |
return NULL; |
25 |
} |
26 |
|
27 |
len = 0;
|
28 |
size = 64;
|
29 |
str = malloc(size); |
30 |
if (!str) {
|
31 |
close(fd); |
32 |
return NULL; |
33 |
} |
34 |
|
35 |
while (1) { |
36 |
nread = read(fd, str+len, size-len); |
37 |
len += nread; |
38 |
if (len == size) {
|
39 |
size *= 2;
|
40 |
str = realloc(str, size); |
41 |
if (!str)
|
42 |
return NULL; |
43 |
} |
44 |
if (nread == 0) { |
45 |
str[len] = '\0';
|
46 |
close(fd); |
47 |
return str;
|
48 |
} else if (nread < 0) { |
49 |
log_perror("read");
|
50 |
free(str); |
51 |
close(fd); |
52 |
return NULL; |
53 |
} |
54 |
} |
55 |
} |
56 |
|
57 |
/*
|
58 |
* create_pid_file
|
59 |
*
|
60 |
* Creates PIDFILE containing the PID of the current process. Returns 0 if
|
61 |
* successful, or nonzero if there is an error or it already exists.
|
62 |
*/
|
63 |
int create_pid_file() {
|
64 |
int fd;
|
65 |
FILE *file; |
66 |
|
67 |
fd = open(PIDFILE, O_CREAT | O_EXCL | O_WRONLY, 0644);
|
68 |
if (fd < 0) { |
69 |
if (errno == EEXIST)
|
70 |
fprintf(stderr, "ERROR: tooltron is already running, or the pidfile "
|
71 |
PIDFILE " is stale");
|
72 |
else
|
73 |
log_perror(PIDFILE); |
74 |
return 1; |
75 |
} |
76 |
|
77 |
file = fdopen(fd, "w");
|
78 |
if (!file) {
|
79 |
log_perror("fdopen");
|
80 |
return 1; |
81 |
} |
82 |
|
83 |
fprintf(file, "%d", getpid());
|
84 |
|
85 |
fclose(file); |
86 |
return 0; |
87 |
} |
88 |
|
89 |
/*
|
90 |
* remove_pid_file
|
91 |
*
|
92 |
* Removes PIDFILE.
|
93 |
*/
|
94 |
void remove_pid_file() {
|
95 |
if (unlink(PIDFILE))
|
96 |
log_perror(PIDFILE); |
97 |
} |
98 |
|
99 |
/*
|
100 |
* read_pid_file
|
101 |
*
|
102 |
* Returns the integer found in PIDFILE, or 0 if there was an
|
103 |
* error.
|
104 |
*/
|
105 |
pid_t read_pid_file() { |
106 |
FILE *file; |
107 |
int pid;
|
108 |
|
109 |
file = fopen(PIDFILE, "r");
|
110 |
if (!file) {
|
111 |
if (errno == ENOENT)
|
112 |
fprintf(stderr, "ERROR: tooltron does not appear to be running\n");
|
113 |
else
|
114 |
perror(PIDFILE); |
115 |
return 0; |
116 |
} |
117 |
|
118 |
if (fscanf(file, "%d", &pid) != 1) { |
119 |
perror("fscanf");
|
120 |
fclose(file); |
121 |
return 0; |
122 |
} |
123 |
|
124 |
fclose(file); |
125 |
return pid;
|
126 |
} |