Skip to content

Instantly share code, notes, and snippets.

@loderunner
Created July 24, 2014 09:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save loderunner/1372bab8060b012b2117 to your computer and use it in GitHub Desktop.
Save loderunner/1372bab8060b012b2117 to your computer and use it in GitHub Desktop.
Retrieve process name from pid using sysctl (Darwin)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/sysctl.h>
int main(int argc, char** argv) {
int mib[3], argmax;
size_t syssize;
char *procargs, *cp, *thiscmd;
mib[0] = CTL_KERN;
mib[1] = KERN_ARGMAX;
syssize = sizeof(argmax);
if (sysctl(mib, 2, &argmax, &syssize, NULL, 0) == -1) {
goto _end;
}
procargs = malloc(argmax);
if (procargs == NULL) {
goto _end;
}
mib[0] = CTL_KERN;
mib[1] = KERN_PROCARGS;
mib[2] = strtol(argv[1], NULL, 10);
syssize = (size_t)argmax;
if (sysctl(mib, 3, procargs, &syssize, NULL, 0) == -1) {
free(procargs);
goto _end;
}
for (cp = procargs; cp < &procargs[syssize]; cp++) {
if (*cp == '\0') {
break;
}
}
if (cp == &procargs[syssize]) {
free(procargs);
goto _end;
}
for (; cp < &procargs[syssize]; cp++) {
if (*cp != '\0') {
break;
}
}
if (cp == &procargs[syssize]) {
free(procargs);
goto _end;
}
/* Strip off any path that was specified */
for (thiscmd = cp; (cp < &procargs[syssize]) && (*cp != '\0'); cp++) {
if (*cp == '/') {
thiscmd = cp + 1;
}
}
printf("%s\n", thiscmd);
_end:
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment