Что эквивалентно / proc / self / exe на Macintosh OS X Mavericks?

Я портирую приложение 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;
}

1

Решение

Вот что я выбрал в качестве решения:

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

Другие решения

Других решений пока нет …