Skip to content

Instantly share code, notes, and snippets.

@haxrob
Created June 30, 2024 09:10
Show Gist options
  • Save haxrob/c31543f78394dc87beb7b29094211e4c to your computer and use it in GitHub Desktop.
Save haxrob/c31543f78394dc87beb7b29094211e4c to your computer and use it in GitHub Desktop.
#### NOTE, this was generated with Claude 3.5 sonnet.
#include <sys/param.h>
#include <sys/sysctl.h>
#include <sys/user.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
char* get_proc_args(pid_t pid) {
int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_ARGS, pid};
static char args[ARG_MAX];
size_t size = ARG_MAX;
if (sysctl(mib, 4, args, &size, NULL, 0) == -1) {
return NULL;
}
return args;
}
int main() {
int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PROC, 0};
size_t size;
struct kinfo_proc *proc;
int count, i;
// Get the size of the buffer needed
if (sysctl(mib, 4, NULL, &size, NULL, 0) < 0) {
perror("sysctl");
exit(1);
}
// Allocate memory for the process information
proc = malloc(size);
if (!proc) {
perror("malloc");
exit(1);
}
// Get the actual process information
if (sysctl(mib, 4, proc, &size, NULL, 0) < 0) {
perror("sysctl");
free(proc);
exit(1);
}
// Calculate the number of processes
count = size / sizeof(struct kinfo_proc);
// Print process information
for (i = 0; i < count; i++) {
printf("PID: %d, Name (ki_comm): %.19s", proc[i].ki_pid, proc[i].ki_comm);
// Get full command line
char *args = get_proc_args(proc[i].ki_pid);
if (args != NULL) {
printf(", Command: %s", args);
}
printf("\n");
}
free(proc);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment