forked from liexusong/bolt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.c
115 lines (91 loc) · 2.47 KB
/
utils.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/*
* Bolt - The Realtime Image Compress System
* Copyright (c) 2015 - 2016, Liexusong <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
int
bolt_file_exists(char *path)
{
return access((const char *)path, F_OK) == 0;
}
void
bolt_daemonize()
{
int fd;
if (fork() != 0) {
exit(0);
}
setsid();
if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
dup2(fd, STDIN_FILENO);
dup2(fd, STDOUT_FILENO);
dup2(fd, STDERR_FILENO);
if (fd > STDERR_FILENO) {
close(fd);
}
}
}
char *
bolt_strndup(char *str, int length)
{
char *retval;
retval = malloc(length + 1);
if (!retval) {
return NULL;
}
memcpy(retval, str, length);
retval[length] = 0;
return retval;
}
int
bolt_atoi(char *start, int length, int *retval)
{
#define BOLT_DIGIT_CHAR(c) ((c) >= '0' && (c) <= '9')
int result;
char *off;
int times;
for (off = start + length - 1, times = 1, result = 0;
off >= start; off--)
{
if (BOLT_DIGIT_CHAR(*off)) {
result += (*off - '0') * times;
times *= 10;
} else {
break;
}
}
if (off > start) {
return -1;
} else if (off == start) {
if (*off == '-') {
result = -result;
} else if (*off != '+') {
return -1;
}
}
if (retval) {
*retval = result;
}
return 0;
#undef BOLT_DIGIT_CHAR
}