【问题标题】:working directory of running process on mac osmac os上运行进程的工作目录
【发布时间】:2012-01-09 18:13:37
【问题描述】:

我想知道 Mac OS (10.6) 上进程的工作目录。我尝试在 ps 命令的输出中查找 PWD 环境变量,但 PWD 变量在那里不可用。有没有更好的方法来为 mac 上正在运行的进程找到这个?

【问题讨论】:

    标签: macos osx-snow-leopard


    【解决方案1】:

    lsof -d cwd 将打印所有进程的当前工作目录。如果您想显示不属于您的进程的信息,您需要以 root 身份运行它(即使用 sudo 作为前缀)。如果您只想显示某些程序或进程的信息,请使用例如lsof -a -d cwd -c programnamelsof -a -d cwd -p processid(注意:在这两种情况下,-a 标志意味着其他标志的限制被“和”在一起)。 lsof 相当复杂并且有更多选择,因此请阅读其手册页了解更多信息。

    【讨论】:

      【解决方案2】:

      如果您是在 Cocoa 程序中进行操作,这将起作用:

      NSFileManager *fm = [[[NSFileManager alloc] init] autorelease];
      NSString *currentPath = [fm currentDirectoryPath];
      

      【讨论】:

        【解决方案3】:

        虽然Gordon Davisson's answer 很棒,但如果您想从代码中实现而不需要调用lsof,这里是您需要的代码。它的灵感来自 lsof 源代码和 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;
        }
        

        此示例代码将产生如下输出:

         proc 44586 executable: /bin/zsh
         proc 44586 cwd: /private/tmp
        

        【讨论】:

          猜你喜欢
          • 2013-09-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-06-14
          • 2012-01-15
          • 2011-06-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多