如何获得相对路径的cwd?

问题描述 投票:6回答:2

对于使用相对路径调用的系统调用,如何在strace输出中获取当前工作目录?我正在尝试调试产生多个进程并且无法打开特定文件的复杂应用程序。

stat("some_file", 0x7fff6b313df0) = -1 ENOENT (No such file or directory)

由于some_file存在,我相信它位于错误的目录中。我也试图跟踪chdir调用,但由于输出是交错的,因此难以推断工作目录。有没有更好的办法?

linux strace
2个回答
1
投票

您可以使用-y选项,它将打印完整路径。在这种情况下另一个有用的标志是-P,它只跟踪与特定路径有关的系统调用,例如

strace -y -P "some_file"

不幸的是-y只打印文件描述符的路径,因为你的调用没有加载任何它没有。一种可能的解决方法是在调试器中运行系统调用时中断进程,然后通过检查/proc/<PID>/cwd来获取其工作目录。像这样的东西(完全未经测试!)

gdb --args strace -P "some_file" -e inject=open:signal=SIGSEGV

或者您可以使用条件断点。像这样的东西应该可以工作,但我很难让GDB在fork之后跟踪子进程。如果你只有一个过程我认为应该没问题。

gdb your_program
break open if $_streq((char*)$rdi, "some_file")
run
print getpid()

-2
投票

这很简单,使用函数char * realpath(const char * path,char * resolved_pa​​th)作为当前目录。

这是我的例子:

#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

int main(){
    char *abs;

    abs = realpath(".", NULL);

    printf("%s\n", abs);
    return 0;
}

产量

root@ubuntu1504:~/patches_power_spec# pwd
/root/patches_power_spec
root@ubuntu1504:~/patches_power_spec# ./a.out 
/root/patches_power_spec
© www.soinside.com 2019 - 2024. All rights reserved.