-
-
Save connectthefuture/2dbcdcf17b015b23599caa6d535778d6 to your computer and use it in GitHub Desktop.
Retrieve process name from pid using sysctl (Darwin)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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