Skip to content

Instantly share code, notes, and snippets.

@antranigv
Last active April 21, 2024 19:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antranigv/fcd2f2c3faa0b986e4d2b781793f6ed1 to your computer and use it in GitHub Desktop.
Save antranigv/fcd2f2c3faa0b986e4d2b781793f6ed1 to your computer and use it in GitHub Desktop.
Get current working directory of a process in FreeBSD in C using libprocstat [no error handling]
// cc getpwd.c -l procstat -o getpwd
#include <sys/param.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/un.h>
#include <sys/user.h>
#include <sys/queue.h>
#include <sys/socket.h>
#include <libprocstat.h>
#include <sys/sysctl.h>
int
main(int argc, char **argv)
{
if (argc < 2)
{
printf("usage: getpwd PID\n");
exit(1);
}
// to int
pid_t pid = atoi(argv[1]);
// Init types
struct filestat_list *head;
struct filestat *fst;
// open sysctl
struct procstat *procstat = procstat_open_sysctl();
// get processes
unsigned int count;
struct kinfo_proc *procs = procstat_getprocs(procstat, KERN_PROC_PID, pid, &count);
// get files from process
head = procstat_getfiles(procstat, &procs[0], 0);
STAILQ_FOREACH(fst, head, next) {
if (fst->fs_uflags & PS_FST_UFLAG_CDIR) {
printf("%s\n", fst->fs_path);
}
}
procstat_close(procstat);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment