本文介绍了在Macintosh OS X Mavericks上相当于/ proc / self / exe是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

在Linux上工作的代码:

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


推荐答案

解决方案:

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

这篇关于在Macintosh OS X Mavericks上相当于/ proc / self / exe是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-19 01:41