4

我有一个getcwd()用于获取当前工作目录的构建系统工具。这很好,只是有时人们的路径中有空格,而构建系统不支持这一点。你会认为你可以只做一个符号链接:

ln -s "Directory With Spaces" DirectoryWithoutSpaces

然后快乐起来。但对我来说不幸的是,getcwd()解决了所有的符号链接。我尝试使用getenv("PWD"),但它指向的路径与我返回的路径不同getcwd()。我认为,我责怪make -C没有更新环境变量。现在,getcwd()给我一条这样的路径:

/Users/carl/Directory With Spaces/Some/Other/Directories

getenv("PWD")给我:

/Users/carl/DirectoryWithoutSpaces

那么 - 是否有任何类似getcwd()的功能不能解决符号链接?

编辑:

我变了

make -C Some/Other/Directories

cd Some/Other/Directories ; make

然后getenv("PWD")工作..如果没有其他解决方案,我可以使用它。

4

2 回答 2

6

根据 Stevens 的《UNIX 环境中的高级编程》圣经,第 112 页:

由于内核必须保持对当前工作目录的了解,我们应该能够获取它的当前值。不幸的是,内核为每个进程维护的只是当前工作目录的 i 节点编号和设备标识。内核不维护目录的完整路径名。

抱歉,看来您确实需要以另一种方式解决此问题。

于 2010-07-17T01:24:45.833 回答
3

无法getcwd()确定您通过符号链接遵循的路径。stats的基本实现getcwd()当前目录' .',然后打开父目录' ..'并扫描条目,直到找到与' .'具有相同inode编号的目录名称。然后它向上重复该过程,直到找到根目录,此时它具有完整路径。它绝不会遍历符号链接。因此,getcwd()通过符号链接计算路径的目标是不可能的,无论是作为系统调用还是作为库函数实现。

The best resolution is to ensure that the build system handles path names containing spaces. That means quoting pathnames passed through the shell. C programs don't care about the spaces in the name; it is only when a program like the shell interprets the strings that you run into problems. (Compilers implemented as shell scripts that run pre-processors often have problems with pathnames that contain spaces - speaking from experience.)

于 2010-07-17T04:37:41.670 回答