diff --git a/src/cpp/core/include/core/system/PosixSystem.hpp b/src/cpp/core/include/core/system/PosixSystem.hpp index 72ff7e9be4e..691dcca6195 100644 --- a/src/cpp/core/include/core/system/PosixSystem.hpp +++ b/src/cpp/core/include/core/system/PosixSystem.hpp @@ -262,6 +262,7 @@ FilePath currentWorkingDirMac(PidType pid); #ifndef __APPLE__ // Determine current working directory of a given process by shelling out // to lsof; used on systems without procfs. +core::Error currentWorkingDirViaLsof(PidType pid, FilePath* pPath); FilePath currentWorkingDirViaLsof(PidType pid); // Determine current working directory of a given process via procfs; returns diff --git a/src/cpp/core/system/PosixSystem.cpp b/src/cpp/core/system/PosixSystem.cpp index 850573277f0..ea06a3b743a 100644 --- a/src/cpp/core/system/PosixSystem.cpp +++ b/src/cpp/core/system/PosixSystem.cpp @@ -1295,8 +1295,10 @@ FilePath currentWorkingDirMac(PidType pid) #ifndef __APPLE__ // NOTE: disabled on macOS; prefer using 'currentWorkingDirMac()' -FilePath currentWorkingDirViaLsof(PidType pid) +Error currentWorkingDirViaLsof(PidType pid, FilePath *pPath) { + *pPath = FilePath(); + // lsof -a -p PID -d cwd -Fn // shell_utils::ShellCommand cmd("lsof"); @@ -1310,12 +1312,13 @@ FilePath currentWorkingDirViaLsof(PidType pid) core::system::ProcessResult result; Error error = runCommand(cmd, options, &result); if (error) - { - LOG_ERROR(error); - return FilePath(); - } + return error; + if (result.exitStatus != 0) - return FilePath(); + return unknownError( + "Failed to run lsof - exited with code " + std::to_string(result.exitStatus) + + (result.stdErr.empty() ? "" : " (" + result.stdErr + ")"), + ERROR_LOCATION); // lsof outputs multiple lines, which varies by platform. We want the one // starting with lowercase 'n', after that is the current working directory. @@ -1327,9 +1330,15 @@ FilePath currentWorkingDirViaLsof(PidType pid) pos++; size_t finalPos = result.stdOut.find_first_of('\n', pos); if (finalPos != std::string::npos) - return FilePath(result.stdOut.substr(pos, finalPos - pos)); + { + *pPath = FilePath(result.stdOut.substr(pos, finalPos - pos)); + return Success(); + } else - return FilePath(result.stdOut.substr(pos)); + { + *pPath = FilePath(result.stdOut.substr(pos)); + return Success(); + } } // next line @@ -1337,7 +1346,20 @@ FilePath currentWorkingDirViaLsof(PidType pid) pos++; } - return FilePath(); + return Success(); +} + + +// NOTE: disabled on macOS; prefer using 'currentWorkingDirMac()' +FilePath currentWorkingDirViaLsof(PidType pid) +{ + FilePath path; + Error error = currentWorkingDirViaLsof(pid, &path); + + if (error) + LOG_ERROR(error); + + return path; } FilePath currentWorkingDirViaProcFs(PidType pid)