linux c++获取当前程序的运行路径

比如我的程序名 为:aaa

存放路径 是:/homo/code/

我在/home/ccc 目录执行shell文件。shell文件的内容为

powershell 复制代码
#!/bin/bash
/homo/code/aaa

希望 获取的路径是 /homo/code/ 而不是脚本的路径

给出完整接口代码

cpp 复制代码
#include <iostream>
#include <string>
#include <string.h>
#include <unistd.h>

#define MAX_PATH_LEN  256

bool getCurrRunningPath(std::string &currPath)
{
    char path[MAX_PATH_LEN] = {0};
    char *p = NULL;
    ssize_t n = readlink("/proc/self/exe", path, MAX_PATH_LEN);
    if (n > 0) {
        p = strrchr(path, '/');
        *(p + 1) = '\0'; // 去掉最后的程序名称
        currPath.assign(path);
        std::cout << "get current running path:" << path << std::endl;
        return true;
    } else {
        std::cout << "get current running path failed, errno: " << errno << std::endl;
    }

    return false;
}

int main()
{
 std::string curpath;
 getCurrRunningPath(curpath);
 std::cout << "***: " << curpath << std::endl;

 return 0;
}
相关推荐
kidwjb1 小时前
信号量在进程中的使用
linux·进程间通信
C+++Python2 小时前
C++ 进阶学习完整指南
java·c++·学习
sparEE2 小时前
c++值类别、右值引用和移动语义
开发语言·c++
sulikey3 小时前
个人Linux操作系统学习笔记2 - gcc与库的理解
linux·笔记·学习·操作系统·gcc·
jrrz08283 小时前
Apollo MPC Controller
c++·自动驾驶·apollo·mpc·横向控制·lateral control
二宝哥3 小时前
Linux虚拟机网络配置
linux·运维·服务器
陳10304 小时前
Linux:进程间通信 和 简单进程池
linux·运维·服务器
jimy14 小时前
改.bashrc,直观地判断本地repo是否有改动
linux·服务器
愚昧之山绝望之谷开悟之坡4 小时前
什么是Linter?什么是沙箱!
linux·笔记
babytiger5 小时前
Gitea 重安装 + Snap 数据迁移完整流程总结
linux·elasticsearch·gitea