2 #include <sys/sysctl.h>
8 #include <WINGs/WUtil.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
)
28 static char *args
= NULL
;
29 static int argmax
= 0;
34 /* the system-wide limit */
35 if (argmax
== 0) { /* it hopefully doesn't change at runtime *g* */
41 count
= sizeof(argmax
);
42 if (sysctl(mib
, 2, &argmax
, &count
, NULL
, 0) == -1)
46 /* if argmax is still 0, something went very seriously wrong */
49 /* space for args; no need to free before returning even on errors */
51 args
= (char *)wmalloc(argmax
);
53 /* get process args */
55 mib
[1] = KERN_PROCARGS2
;
59 if (sysctl(mib
, 3, args
, &count
, NULL
, 0) == -1 || count
== 0)
63 memcpy(argc
, args
, sizeof(*argc
));
66 while (args
[idx
++] != '\0') /* skip execname */
68 while (args
[idx
] == '\0') /* padding too */
70 /* args[idx] is at at begininng of args now */
76 while(*p
!= '\0') p
++; // look for the next \0
77 while(*p
== '\0') p
++; // skip over padding \0s
86 // At this point, p points to the last \0 in the source array.
88 // Buffer needed for the strings
89 unsigned stringbuf_size
= p
- &args
[idx
];
91 // Buffer needed for the pointers (plus one terminating NULL)
92 unsigned pointerbuf_size
= sizeof(char *) * (*argc
+ 1);
94 *argv
= wmalloc(pointerbuf_size
+ stringbuf_size
);
95 char* stringstart
= (char *)(*argv
) + pointerbuf_size
;
97 memcpy(stringstart
, &args
[idx
], stringbuf_size
);
105 while(*p
!= '\0') p
++; // look for the next \0
106 while(*p
== '\0') p
++; // skip over padding \0s
110 (*argv
)[found
] = NULL
; // Terminating NULL
114 #else /* !KERN_PROCARGS2 */