Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

freebsd

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.

like image 842
Raphael Ahrens Avatar asked Nov 26 '14 09:11

Raphael Ahrens


People also ask

How do you check the current working directory that are is using?

pwd (print working directory) – The pwd command is used to display the name of the current working directory in the Linux system using the terminal. This is a shell building command that is available in most Unix shells such as Bourne shell, ash, bash, kash, and zsh.

How do I find my PID path?

We can get the PID of a process with the help of the ps command. Let's start an editor process and get its PID using the ps command: $ gedit test.

What method is used to return the current working directory of the process?

The pwd command will return the current working directory.


1 Answers

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.

like image 94
user3159253 Avatar answered Oct 24 '22 03:10

user3159253