change sockaddr generation to pass around correct types.
[trinity.git] / pids.c
blobafbd15ce345d42bcbdd5aeae9ac6cec53cbe11f4
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"
11 pid_t initpid;
13 int find_pid_slot(pid_t mypid)
15 unsigned int i;
17 for_each_pidslot(i) {
18 if (shm->pids[i] == mypid)
19 return i;
21 return PIDSLOT_NOT_FOUND;
24 bool pidmap_empty(void)
26 unsigned int i;
28 for_each_pidslot(i) {
29 if (shm->pids[i] != EMPTY_PIDSLOT)
30 return FALSE;
32 return TRUE;
35 void dump_pid_slots(void)
37 unsigned int i, j = 0;
38 char string[512], *sptr = string;
40 sptr += sprintf(sptr, "## pids: (%d active)\n", shm->running_childs);
42 for (i = 0; i < shm->max_children; i+=8) {
43 sptr += sprintf(sptr, "%d-%d: ", i, i+7);
44 for (j = 0; j < 8; j++) {
45 if (shm->pids[i+j] != EMPTY_PIDSLOT) {
46 if (pid_alive(shm->pids[i+j] == -1))
47 RED
50 sptr += sprintf(sptr, "%d ", shm->pids[i+j]);
51 CRESET
53 sptr += sprintf(sptr, "\n");
55 *sptr = '\0';
56 outputerr("%s", string);
59 static pid_t pidmax;
61 static int read_pid_max(void)
63 unsigned long result;
64 char *end, buf[32];
65 FILE *fp;
66 int rc;
68 fp = fopen("/proc/sys/kernel/pid_max", "r");
69 if (!fp) {
70 perror("fopen");
71 return -1;
74 rc = -1;
75 if (!fgets(buf, sizeof(buf), fp))
76 goto out;
78 result = strtoul(buf, &end, 10);
79 if (end == buf)
80 goto out;
82 pidmax = result;
83 rc = 0;
84 out:
85 fclose(fp);
86 return rc;
89 void pids_init(void)
91 if (read_pid_max()) {
92 #ifdef __x86_64__
93 pidmax = 4194304;
94 #else
95 pidmax = 32768;
96 #endif
97 outputerr("Couldn't read pid_max from proc\n");
100 output(0, "Using pid_max = %d\n", pidmax);
103 int pid_is_valid(pid_t pid)
105 if ((pid > pidmax) || (pid < 1)) {
106 output(0, "Sanity check failed! Found pid %d!\n", pid);
107 return FALSE;
110 return TRUE;
113 unsigned int get_pid(void)
115 unsigned int i;
116 pid_t pid = 0;
118 /* If we get called from the parent, and there are no
119 * children around yet, we need to not look at the pidmap. */
120 if (shm->running_childs == 0)
121 return 0;
123 switch (rand() % 3) {
124 case 0:
125 retry: i = rand() % shm->max_children;
126 pid = shm->pids[i];
127 if (pid == EMPTY_PIDSLOT)
128 goto retry;
129 break;
131 case 1: pid = 0;
132 break;
134 case 2: if (dangerous == FALSE) // We don't want root trying to kill init.
135 pid = 1;
136 break;
138 default:
139 break;
142 return pid;