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