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;
}
相关推荐
Zenova EdgeOS3 小时前
Linux 内核日志 dmesg 进阶实战:从现场过滤到持久化闭环
linux·运维·服务器
郝亚军3 小时前
ec_private.pem的生成方法
linux·运维·服务器
NendoZen4 小时前
Arch Linux解决Grub无法SAVEDEFAULT问题(uki启动问题)
linux·运维·服务器
努力实干5 小时前
面向对象设计原则——C++
开发语言·c++·数码相机
忆挽篱笙歌5 小时前
进程控制管理
linux·运维·服务器
Escalating_xu5 小时前
【Linux 网络编程】connect 的断线重连:用状态机写一个能恢复连接的 TCP 客户端
linux·网络·tcp/ip
Zucker n6 小时前
英语“论文”语法检查工具
linux·windows
苏宸啊7 小时前
Reactor反应堆模式
linux
syagain_zsx7 小时前
jsoncpp 使用指南:编译链接、Json::Value 取值与高频坑
c++·json·库·http格式
骇客野人8 小时前
Linux 全套实操方案(含目录详解、文件传输、日志、文件规范、环境变量、Java 应用部署运维)
java·linux·运维