【问题标题】:What is the equivalent of /proc/self/exe on Macintosh OS X Mavericks?Macintosh OS X Mavericks 上的 /proc/self/exe 等价物是什么?
【发布时间】:2014-05-05 17:00:39
【问题描述】:

我正在将一个 Linux C++03 应用程序移植到 Darwin OS X,并且有一些代码可以读取 /proc/self/exe 处的符号链接以确定运行的可执行文件所在的目录。

如何计算当前在 Macintosh Darwin OS X Mavericks 上运行的 C++ 可执行文件的目录?

这是我现有的适用于 Linux 的代码:

bool
resolveBinaryLocation(string &binaryDirname)
{
  // Read the symbolic link '/proc/self/exe'.
  const char *linkName = "/proc/self/exe";
  const size_t bufSize = PATH_MAX + 1;
  char dirNameBuffer[bufSize];
  const int ret = int(readlink(linkName, dirNameBuffer, bufSize - 1));

  if (ret == -1) {
    // Permission denied (We must be inetd with this app run as other than root).
    return false;
  }

  dirNameBuffer[ret] = 0; // Terminate the string with a NULL character.

  binaryDirname = dirNameBuffer;

  // Erase the name of the executable:
  string::size_type last = binaryDirname.size() - 1;
  string::size_type idx  = binaryDirname.rfind(DSI_PATH_CHAR, last);

  // Add one to keep the trailing directory separator.
  binaryDirname.erase(idx + 1);

  return true;
}

【问题讨论】:

标签: c++ osx-mavericks porting c++03 darwin


【解决方案1】:

以下是我确定的解决方案:

bool
resolveBinaryLocation(string &binaryDirname)
{
  const size_t bufSize = PATH_MAX + 1;
  char dirNameBuffer[bufSize];

#ifdef __APPLE__
  uint32_t size = bufSize;

  if (_NSGetExecutablePath(dirNameBuffer, &size) != 0) {
    // Buffer size is too small.
    return false;
  }
#else // not __APPLE__
  // Read the symbolic link '/proc/self/exe'.
  const char *linkName = "/proc/self/exe";
  const int ret = int(readlink(linkName, dirNameBuffer, bufSize - 1));

  if (ret == -1) {
    // Permission denied (We must be inetd with this app run as other than root).
    return false;
  }
    
  dirNameBuffer[ret] = 0; // Terminate the string with a NULL character.
#endif // else not __APPLE__

  binaryDirname = dirNameBuffer;

  // Erase the name of the executable:
  string::size_type last = binaryDirname.size() - 1;
  string::size_type idx  = binaryDirname.rfind(DSI_PATH_CHAR, last);

  // Add one to keep the trailing directory separator.
  binaryDirname.erase(idx + 1);

  return true;
}

【讨论】:

  • 不要使用非标准的#ifdef ARCH_darwin_14_i86,最好还是使用标准的#ifdef __APPLE__
  • @SimonKissane 已更新。
猜你喜欢
  • 2012-08-09
  • 2011-05-04
  • 2016-04-25
  • 2012-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-27
  • 1970-01-01
相关资源
最近更新 更多