file:get_cwd() 出现 {error, enoent} 的常见原因是什么?

What are common causes for getting {error, enoent} for file:get_cwd()?

我正在使用 file:get_cwd(),但我发现它有错误,即 {error, enoent}。导致此错误的潜在问题可能是什么?

如果您查看用于在此类系统上实现 file:get_cwd/0UNIX manual page for getcwd(3),您会发现以下对 ENOENT 错误结果的解释:

ENOENT The current working directory has been unlinked.

换句话说,如果当前工作目录已从Erlang进程下删除,就会出现此错误。在 documentation for the file module.

中存在许多对 enoent 的类似解释

尝试从 erl shell 进行以下调用序列,假设目录 /tmp/foo 在您的系统上尚不存在:

1> file:make_dir("/tmp/foo").
ok
2> cd("/tmp/foo").
/tmp/foo
ok
3> file:get_cwd().
{ok,"/tmp/foo"}
4> file:del_dir("/tmp/foo").
ok
5> file:get_cwd().
{error,enoent}

此序列首先创建新目录 /tmp/foo 并将 erl 进程的工作目录更改为该目录。第一次调用 file:get_cwd() 确认 /tmp/foo 是工作目录,正如预期的那样。然后通过调用 file:del_dir/1 删除目录。因为工作目录现在不再存在,所以第二次调用 file:get_cwd() returns {error,enoent}.