GetCommandForPid() for darwin/osx
[wmaker-crm.git] / src / osdep / darwin.c
blobe037b5df4f6838a0cf721acfb938bcee8aa6af8c
2 #include <sys/types.h>
3 #include <sys/sysctl.h>
5 #include <assert.h>
6 #include <stdlib.h>
7 #include <string.h>
9 /*
10 * copy argc and argv for an existing process identified by `pid'
11 * into suitable storage given in ***argv and *argc.
13 * subsequent calls use the same static area for argv and argc.
15 * returns 0 for failure, in which case argc := 0 and argv := NULL
16 * returns 1 for success
18 Bool GetCommandForPid(int pid, char ***argv, int *argc)
19 #ifdef KERN_PROCARGS2
21 int j, mib[4];
22 unsigned int i, idx;
23 size_t count;
24 static char *args = NULL;
25 static int argmax = 0;
27 *argv = NULL;
28 *argc = 0;
30 /* the system-wide limit */
31 if (argmax == 0) { /* it hopefully doesn't change at runtime *g* */
32 mib[0] = CTL_KERN;
33 mib[1] = KERN_ARGMAX;
34 mib[2] = 0;
35 mib[3] = 0;
37 count = sizeof(argmax);
38 if (sysctl(mib, 2, &argmax, &count, NULL, 0) == -1)
39 return False;
42 /* if argmax is still 0, something went very seriously wrong */
43 assert(argmax > 0);
45 /* space for args; no need to free before returning even on errors */
46 if (args == NULL)
47 args = (char *)wmalloc(argmax);
49 /* get process args */
50 mib[0] = CTL_KERN;
51 mib[1] = KERN_PROCARGS2;
52 mib[2] = pid;
54 count = argmax;
55 if (sysctl(mib, 3, args, &count, NULL, 0) == -1 || count == 0)
56 return False;
58 /* get argc, skip */
59 memcpy(argc, args, sizeof(*argc));
60 idx = sizeof(*argc);
62 while (args[idx++] != '\0') /* skip execname */
64 while (args[idx] == '\0') /* padding too */
65 idx++;
66 /* args[idx] is at at begininng of args now */
68 *argv = (char **)wmalloc(sizeof(char *) * (*argc + 1 /* term. null ptr */));
69 (*argv)[0] = args + idx;
71 /* go through args, set argv[$next] to the beginning of each string */
72 for (i = 0, j = 1; i < count - idx /* do not overrun */; i++) {
73 if (args[idx + i] != '\0')
74 continue;
75 if (args[idx + i] == '\0')
76 (*argv)[j++] = &args[idx + i + 1];
77 if (j == *argc)
78 break;
81 /* the list of arguments must be terminated by a null pointer */
82 (*argv)[j] = NULL;
83 return True;
85 #else /* !KERN_PROCARGS2 */
87 *argv = NULL;
88 *argc = 0;
90 return False;
92 #endif