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;
}
相关推荐
٩( 'ω' )و2604 分钟前
linux--库的制作与原理
linux
海盗123420 分钟前
VMware 中 CentOS 7 无法使用 yum 安装 wget 的完整解决方案
linux·运维·centos
人工智能AI技术42 分钟前
GitHub Copilot 2026新功能实操:C++跨文件上下文感知开发,效率翻倍技巧
c++·人工智能
gtr20201 小时前
Ubuntu24.04 基于 EtherCAT 的 SVD60N 主站
linux·ethercat
weixin_462446231 小时前
ubuntu真机安装tljh jupyterhub支持跨域iframe
linux·运维·ubuntu
小码吃趴菜1 小时前
select/poll/epoll 核心区别
linux
大志若愚YYZ1 小时前
ROS2学习 C++中的this指针
c++·学习·算法
Ghost Face...1 小时前
深入解析网卡驱动开发与移植
linux·驱动开发
a41324471 小时前
在CentOS系统上挂载硬盘到ESXi虚拟机
linux·运维·centos
MMME~1 小时前
Linux下的软件管理
linux·运维·服务器