Raphael Ahrens
Raphael Ahrens

Reputation: 992

How to get the current working directory of a process in FreeBSD in C?

Currently I'm trying to port a terminal emulator written in C from Linux to FreeBSD. But the terminal tries to get the current working directory (CWD) from the parent process.

It does this by accessing /proc/$PID/cwd.

Now I'm looking for a way to replace this functionalty with something that works on FreeBSD.

So how do I get the CWD from a process in FreeBSD?

Is there even a POSIX conform solution?

I know that I can get the CWD from my process with getcwd but I need the CWD of the parent process, where I only know the PID.

Upvotes: 5

Views: 1494

Answers (1)

user3159253
user3159253

Reputation: 17455

Well, actually you have two possibilities. One of them is to use shell utilities like lsof -p, fstat -p (as I mentioned in the comment above) or another utility named procstat as described here. With procstat the solution will look like this:

procstat -f <pid> | awk '$3 == "cwd" { print $10 }'

another possible solution is to use libprocstat library call, particularly procstat_getfiles() to get the complete info in your C program. Take a look at procstat sources to get an example of API usage.

Upvotes: 5

Related Questions