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

2

6

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)

Parhelion answered 5/10, 2009 at 16:53 Comment(0)
R
10

On 10.5 and later:

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

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

Rimose answered 13/11, 2009 at 3:51 Comment(0)
C
1

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

Continuation answered 6/10, 2009 at 20:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.