I want to know the working directory of a process on Mac OS (10.6). I tried finding the PWD environment variable in ps command's output, but the PWD variable is not available there. Is there a better way to find this for a running process on mac?
3 Answers
lsof -d cwd
will print the current working directories for all of your processes. If you want to show info on processes you don't own, you need to run it as root (i.e. use sudo
as a prefix). If you want to show the info for only certain programs or processes, use e.g. lsof -a -d cwd -c programname
or lsof -a -d cwd -p processid
(note: in both cases, the -a
flag means that the other flags' restrictions get "and"ed together). lsof
is pretty complex and has lots more options, so read its man page for more info.

- 118,432
- 16
- 123
- 151
Although Gordon Davisson's answer is great, if you want to do it from code without calling out to lsof
, here's the code you need. It's inspired by the lsof source and this blog post.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <libproc.h>
int main (int argc, char* argv[])
{
int ret;
pid_t pid;
char pathbuf[PROC_PIDPATHINFO_MAXSIZE];
struct proc_vnodepathinfo vpi;
if (argc > 1) {
pid = (pid_t) atoi(argv[1]);
ret = proc_pidpath (pid, pathbuf, sizeof(pathbuf));
if (ret <= 0) {
fprintf(stderr, "PID %d: proc_pidpath ();\n", pid);
fprintf(stderr, " %s\n", strerror(errno));
return 1;
}
printf("proc %d executable: %s\n", pid, pathbuf);
ret = proc_pidinfo(pid, PROC_PIDVNODEPATHINFO, 0, &vpi,
sizeof(vpi));
if (ret <= 0) {
fprintf(stderr, "PID %d: proc_pidinfo ();\n", pid);
fprintf(stderr, " %s\n", strerror(errno));
return 1;
}
printf("proc %d cwd: %s\n", pid, vpi.pvi_cdir.vip_path);
// printf("proc %d root: %s\n", pid, vpi.pvi_rdir.vip_path);
}
return 0;
}
This sample code will produce output like this:
proc 44586 executable: /bin/zsh
proc 44586 cwd: /private/tmp
If you're talking about doing it within a Cocoa program, this will work:
NSFileManager *fm = [[[NSFileManager alloc] init] autorelease];
NSString *currentPath = [fm currentDirectoryPath];

- 10,550
- 5
- 46
- 72