views:

570

answers:

2

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)

A: 

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).

sakra
+2  A: 

On 10.5 and later:

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

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

yakovlev