I'm using the getcwd function to retrieve the current working directory of my application. In some cases it fails and errno is ENOENT. I call getcwd from different threads, but serially and sometimes I face with ENOENT, but I don't know why. The link above says that ENOENT means that "The current working directory has been unlinked." but the directory exists.
Here is a snippet of the function I use:
UPDATE: Code updated with advice from @Aganju and @molbdnilo:
std::string get_working_dir()
{
char buf[PATH_MAX];
memset(buf, 0, sizeof(buf));
char * result = getcwd(buf, sizeof(buf));
std::string working_path = buf;
// Check for possible errors.
if (result == NULL)
{
switch (errno)
{
case EACCES:
break;
case EFAULT:
break;
case EINVAL:
break;
case ENAMETOOLONG:
break;
case ENOENT:
{
if (working_path.empty())
{
const char* pwd = getenv("PWD");
working_path = (pwd) ? pwd : "";
}
break;
}
case ERANGE:
break;
default:
break;
}
return working_path;
}
}
In case I face ENOENT, I retrieve the "PWD" environment variable because I work on CentOS 5.11 and Ubuntu 16.04, and when getcwd fails on CentOS it returns an empty buffer.
UPDATE:
I have noticed that the call from the main thread does not fail, but when I call the function from another thread it fails and errno is ENOENT.