Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the current working directory of process with a pid programmatically on OS X

Is there a way to get the current working directory of a process using it's PID programmatically on OS X?

Cocoa, Carbon, or AppleScript are all acceptable.

It is not acceptable to send "pwd" to the current terminal window/tab (Do not want to affect the workspace).

The linux command "pwdx" also is also unacceptable (just in case you read over the "Cocoa" part)

like image 403
Corey Floyd Avatar asked Oct 05 '09 16:10

Corey Floyd


2 Answers

On 10.5 and later:

lsof -a -p $PID -d cwd -Fn

(Prefix with sudo if the process is owned by root.)

like image 122
yakovlev Avatar answered Nov 02 '22 02:11

yakovlev


The following AppleScript is a partial solution for your problem. Given the UNIX pid in the variable thePID it first gets the name of the process. It then sends the do shell script command to the application process which will result in a child shell process being spawned. The child process inherits the current directory which can then be determined by running the pwd command.

tell application "System Events"
    set theName to name of first process whose unix id is thePID
end tell

tell application theName
    do shell script "/bin/pwd"
end tell

The script does not work for processes that do not link to the AppleEvent framework (e.g., pure POSIX processes).

like image 28
sakra Avatar answered Nov 02 '22 03:11

sakra