What is the equivalent of /proc/self/exe on Macintosh OS X Mavericks?

浪子不回头ぞ 提交于 2019-12-23 02:44:38

问题


I'm porting a Linux C++03 application to Darwin OS X and have some code that reads the symbolic link at /proc/self/exe to determine the directory in which the executable running is located.

How can I compute the directory of the current executable running on Macintosh Darwin OS X Mavericks in C++?

Here is my existing code that works on 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;
}

回答1:


Here is what I settled upon as a solution:

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

#ifdef ARCH_darwin_14_i86
  uint32_t size = bufSize;

  if (_NSGetExecutablePath(dirNameBuffer, &size) != 0) {
    // Buffer size is too small.
    return false;
  }
#else // not ARCH_darwin_14_i86
  // 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 ARCH_darwin_14_i86

  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;
}


来源:https://stackoverflow.com/questions/22675457/what-is-the-equivalent-of-proc-self-exe-on-macintosh-os-x-mavericks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!