-
Notifications
You must be signed in to change notification settings - Fork 241
/
utils.c
130 lines (111 loc) · 2.33 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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "debug.h"
#include "pids.h"
#include "random.h"
#include "shm.h"
#include "utils.h"
/*
* Use this allocator if you have an object a child writes to that you want
* all other processes to see.
*/
void * alloc_shared(unsigned int size)
{
void *ret;
ret = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_ANON | MAP_SHARED, -1, 0);
if (ret == MAP_FAILED) {
printf("mmap %u failure\n", size);
exit(EXIT_FAILURE);
}
/* poison, to force users to set it to something sensible. */
memset(ret, rnd(), size);
return ret;
}
void * __zmalloc(size_t size, const char *func)
{
void *p;
p = malloc(size);
if (p == NULL) {
/* Maybe we mlockall'd everything. Try and undo that, and retry. */
munlockall();
p = malloc(size);
if (p != NULL)
goto done;
printf("%s: malloc(%zu) failure.\n", func, size);
exit(EXIT_FAILURE);
}
done:
memset(p, 0, size);
return p;
}
void sizeunit(unsigned long size, char *buf)
{
/* non kilobyte aligned size? */
if (size & 1023) {
sprintf(buf, "%lu bytes", size);
return;
}
/* < 1MB ? */
if (size < (1024 * 1024)) {
sprintf(buf, "%luKB", size / 1024);
return;
}
/* < 1GB ? */
if (size < (1024 * 1024 * 1024)) {
sprintf(buf, "%ldMB", (size / 1024) / 1024);
return;
}
sprintf(buf, "%ldGB", ((size / 1024) / 1024) / 1024);
}
void kill_pid(pid_t pid)
{
int ret;
int childno;
if (pid == -1) {
show_backtrace();
syslogf("kill_pid tried to kill -1!\n");
return;
}
if (pid == 0) {
show_backtrace();
syslogf("tried to kill_pid 0!\n");
return;
}
childno = find_childno(pid);
if (childno != CHILD_NOT_FOUND) {
if (shm->children[childno]->dontkillme == TRUE)
return;
}
ret = kill(pid, SIGKILL);
if (ret != 0)
debugf("couldn't kill pid %d [%s]\n", pid, strerror(errno));
}
void freeptr(unsigned long *p)
{
void *ptr = (void *) *p;
if (ptr != NULL)
free(ptr);
*p = 0L;
}
int get_num_fds(void)
{
int fd_count;
char buf[64];
struct dirent *dp;
snprintf(buf, 64, "/proc/%i/fd/", mainpid);
fd_count = 0;
DIR *dir = opendir(buf);
while ((dp = readdir(dir)) != NULL) {
fd_count++;
}
closedir(dir);
return fd_count;
}