关于linux:Linux中获取当前进程的绝对路径

45次阅读

共计 609 个字符,预计需要花费 2 分钟才能阅读完成。

  • 通过 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<size_t>(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;
    }

正文完
 0