Skip to content

Commit

Permalink
add wd via LSOF function that returns error
Browse files Browse the repository at this point in the history
  • Loading branch information
MariaSemple committed Nov 14, 2022
1 parent 4c8b36a commit 44b2fdf
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 9 deletions.
1 change: 1 addition & 0 deletions src/cpp/core/include/core/system/PosixSystem.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
40 changes: 31 additions & 9 deletions src/cpp/core/system/PosixSystem.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand All @@ -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.
Expand All @@ -1327,17 +1330,36 @@ 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
pos = result.stdOut.find_first_of('\n', pos);
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)
Expand Down

0 comments on commit 44b2fdf

Please sign in to comment.