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;
}
相关推荐
星火开发设计15 小时前
类模板:实现通用数据结构的基础
java·开发语言·数据结构·c++·html·知识
RisunJan15 小时前
Linux命令-lspci(显示当前主机的所有PCI总线信息)
linux·运维·服务器
寻寻觅觅☆16 小时前
东华OJ-基础题-122-循环数(C++)-难度难
开发语言·c++
王老师青少年编程16 小时前
2022年信奥赛C++提高组csp-s初赛真题及答案解析(完善程序第2题)
c++·题解·真题·初赛·信奥赛·csp-s·提高组
kaka__5516 小时前
cma内存申请页迁移流程浅析
linux
未既16 小时前
linux以及docker修改文件描述符
linux·运维·docker
yuanmenghao16 小时前
Linux 性能实战 | 第 20 篇:trace-cmd 与 kernelshark 可视化分析 [特殊字符]
linux·python·性能优化
plus4s16 小时前
2月13日(73-75题)
数据结构·c++·算法
2401_8735878216 小时前
Linux——传输层协议TCP
linux·网络·tcp/ip
嵌入小生00716 小时前
进程(2)---相关函数接口、消亡、exec函数族 | 嵌入式(Linux)
linux·c语言·嵌入式·进程·函数接口·exec函数族·进程的消亡