move_pages: clear old pointers after freeing
[trinity.git] / pids.c
blob7e6f8fdf35935b83dcbfcae578b169cd5aa20b8c
1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <sys/types.h>
4 #include <signal.h>
5 #include "shm.h"
6 #include "params.h" // for 'dangerous'
7 #include "pids.h"
8 #include "log.h"
9 #include "sanitise.h"
10 #include "trinity.h"
12 pid_t initpid;
14 int find_pid_slot(pid_t mypid)
16 unsigned int i;
18 for_each_pidslot(i) {
19 if (shm->pids[i] == mypid)
20 return i;
22 return PIDSLOT_NOT_FOUND;
25 bool pidmap_empty(void)
27 unsigned int i;
29 for_each_pidslot(i) {
30 if (shm->pids[i] != EMPTY_PIDSLOT)
31 return FALSE;
33 return TRUE;
36 void dump_pid_slots(void)
38 unsigned int i, j = 0;
39 char string[512], *sptr = string;
41 sptr += sprintf(sptr, "## pids: (%u active)\n", shm->running_childs);
43 for (i = 0; i < max_children; i += 8) {
44 sptr += sprintf(sptr, "%u-%u: ", i, i+7);
45 for (j = 0; j < 8; j++) {
46 if (shm->pids[i+j] != EMPTY_PIDSLOT) {
47 if (pid_alive(shm->pids[i+j] == -1))
48 RED
51 sptr += sprintf(sptr, "%d ", shm->pids[i+j]);
52 CRESET
54 sptr += sprintf(sptr, "\n");
56 *sptr = '\0';
57 outputerr("%s", string);
60 static pid_t pidmax;
62 static int read_pid_max(void)
64 unsigned long result;
65 char *end, buf[32];
66 FILE *fp;
67 int rc;
69 fp = fopen("/proc/sys/kernel/pid_max", "r");
70 if (!fp) {
71 perror("fopen");
72 return -1;
75 rc = -1;
76 if (!fgets(buf, sizeof(buf), fp))
77 goto out;
79 result = strtoul(buf, &end, 10);
80 if (end == buf)
81 goto out;
83 pidmax = result;
84 rc = 0;
85 out:
86 fclose(fp);
87 return rc;
90 void pids_init(void)
92 if (read_pid_max()) {
93 #ifdef __x86_64__
94 pidmax = 4194304;
95 #else
96 pidmax = 32768;
97 #endif
98 outputerr("Couldn't read pid_max from proc\n");
101 output(0, "Using pid_max = %d\n", pidmax);
104 int pid_is_valid(pid_t pid)
106 if ((pid > pidmax) || (pid < 1)) {
107 output(0, "Sanity check failed! Found pid %d!\n", pid);
108 return FALSE;
111 return TRUE;
114 unsigned int get_pid(void)
116 unsigned int i;
117 pid_t pid = 0;
119 /* If we get called from the parent, and there are no
120 * children around yet, we need to not look at the pidmap. */
121 if (shm->running_childs == 0)
122 return 0;
124 switch (rand() % 3) {
125 case 0:
126 retry: i = rand() % max_children;
127 pid = shm->pids[i];
128 if (pid == EMPTY_PIDSLOT)
129 goto retry;
130 break;
132 case 1: pid = 0;
133 break;
135 case 2: if (dangerous == FALSE) // We don't want root trying to kill init.
136 pid = 1;
137 break;
140 return pid;