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;
}
相关推荐
0+1114 小时前
Linux --从 poll 到 epoll多路转接
linux·服务器·1024程序员节
青瓦梦滋4 小时前
WebSocket协议
linux·服务器·网络·c++·websocket·网络协议·http
2601_949847757 小时前
bcrypt.js 跨端三方库仓颉适配全流程
linux·运维·ubuntu
m0_639906947 小时前
Linux 操作系统入门:目录结构、服务排查常用命令、Shell 脚本基础
linux·运维·后端
水饺编程9 小时前
第2章:Linux 基础,exit 命令
linux·c语言·汇编
木子欢儿9 小时前
Debian 13 + vsftpd 搭建FTP服务
linux·服务器·前端·网络·debian
CodeYp20199 小时前
第15讲:二叉搜索树
开发语言·c++·二叉搜索树
pipixia2003310 小时前
C++继承面试四连问:内存叠加、私有继承、sizeof、权限重映射
c++·面试·嵌入式·继承·面向对象·对象模型
GeW10 小时前
新质生产力落地实践:企业级Linux迁移与数据库国产化
linux
雯宝10 小时前
usb_serial_generic_register
linux