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;
}
相关推荐
OPEN-F几秒前
C++工程化:编译链接、调试与性能优化
开发语言·c++
瞬间&永恒~1 分钟前
【Kubernetes】(十五)维护与升级、ETCD 备份和恢复
linux·运维·docker·云原生·kubernetes
susplus10 分钟前
【linux应用软件编程】进程间的通信方式2【网络通信从入门到UDP编程】
linux·udp·ip
MSTcheng.10 分钟前
【Linux】Linux学习第三弹——Linux基本指令2
linux·windows·学习·ubuntu·操作系统
希望奇迹很安静16 分钟前
Linux基本使用命令
linux·运维·服务器
邪修king22 分钟前
Re:Linux 系统篇(十七):进程篇(六):环境变量深度解析|命令行参数、环境变量表、4 种获取方式与继承机制万字详解
linux·服务器·c++
张小姐的猫1 小时前
【C++开发脚手架】 —— Jsoncpp上手
java·linux·开发语言·网络·c++·tcp/ip·udp
昌原的儿子LEO1 小时前
Linux网络编程:TCP/UDP与HTTP协议核心笔记
linux·网络·tcp/ip
OPEN-F1 小时前
C++并发编程:异步任务与线程池实战
开发语言·c++·算法
好评1241 小时前
【Linux】应用层协议HTTP
linux·运维·http