Linux中获取当前进程的绝对路径

  • 通过readlink的方式获取。

    bool GetExePath(std::string &path)
    {
      std::string exe_path(PATH_MAX, std::string::value_type());
      auto exe_path_len = readlink("/proc/self/exe", &exe_path[0], exe_path.size());
      if (exe_path_len < 0) {
          std::cerr << "readlink failed!, exe_path_len < 0"<< std::endl;
          return false;
      } else if (static_cast(exe_path_len) >= exe_path.size()) {
          std::cerr << "readlink failed!, exe_path_len >= exe_path.size()"<< std::endl;
          return false;
      }
    
      exe_path.resize(exe_path_len);
      auto pos = exe_path.rfind('/');
      if (pos == std::string::npos) {
          std::cerr << "exe_path.rfind fail!, exe_path.rfind = npos"<< std::endl;
          return false;
      }
      path = exe_path.substr(0, pos);
      return true;
    }

你可能感兴趣的:(linuxc++)