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;
}
相关推荐
huoxingwen29 分钟前
Ubuntu 22.04 上 VMware Workstation 点击虚拟机窗口就消失的解决历程
linux·运维·ubuntu
姚青&1 小时前
Linux 常用命令之基本命令
linux·运维·服务器
DARLING Zero two♡1 小时前
接入 AI Ping 限免接口,让 GLM-4.7 与 MiniMax-M2.1 成为你的免费 C++ 审计专家
开发语言·c++·人工智能
一路往蓝-Anbo1 小时前
【第05期】数据的微观世界 (五) —— 浮点数 vs 定点数:MCU的数学课
linux·stm32·单片机·嵌入式硬件·物联网
G_H_S_3_1 小时前
【网络运维】企业级监控平台Zabbix:部署与实践指南
linux·运维·网络·zabbix
小周学学学1 小时前
Vcenter Auto Deploy安装与使用
linux·运维·服务器
程序喵大人1 小时前
constexpr
开发语言·c++·constexpr
Larry_Yanan1 小时前
Qt多进程(五)QUdpSocket
开发语言·c++·qt·学习·ui
微爱帮监所写信寄信1 小时前
微爱帮监狱写信寄信工具服务器【Linux篇章】再续:TCP协议——用技术隐喻重构网络世界的底层逻辑
linux·服务器·开发语言·网络·网络协议·小程序·监狱寄信
冰西瓜6002 小时前
STL——vector
数据结构·c++·算法