如何在OpenBSD上获取可执行文件路径?

时间:2015-07-18 19:42:30

标签: c openbsd

我试过了:

char *path = realpath(getenv("_"), NULL);
*(strrchr(path, '/')+1) = '\0';

这有效,但如果我的可执行文件由父进程调用, 然后显示父进程的路径。

我搜索了很多,但我找不到任何正常工作的解决方案。

/proc是不可取的。

2 个答案:

答案 0 :(得分:1)

经过一些实验,我认为我有一个有效的解决方案......

An error occurred trying to connect: Post https://192.168.59.103:2376/v1.19/containers/create: remote error: bad certificate

答案 1 :(得分:0)

遗憾的是,无法在OpenBSD中获取已执行文件的完整路径。

按惯例的第一个参数指向文件名,而不是完整路径,并且您无法确定父进程是否遵循该约定。

以下命令,称为exe,说明了这一点。

#include <stdio.h>
#include <fcntl.h>
#include <limits.h>
#include <stdlib.h>
#include <sys/wait.h>

int exe( const char * path, const char * fakepath )
{
    pid_t pid = vfork( ) ;
    if( pid == 0 )
    {
        /* Child process */
        int fd ;
        const int TO = getdtablesize( ) ;
        for( fd = 0 ; fd <= TO ; fd++ )
        {
            close( fd );
        }
        open( "/dev/tty", O_RDONLY ) ;
        open( "/dev/tty", O_WRONLY ) ;
        open( "/dev/tty", O_WRONLY ) ;
        const char *arguments[2] = { fakepath, NULL } ;
        execvp( path, (char**)arguments ) ;
        perror( "exe" ) ;
        exit( 1 ) ;
    }
    else if( pid > 0 )
    {
        /* Parent process */
        int status = 0 ;
        if( waitpid( pid, &status, 0 ) != -1 )
        {
            if( WIFEXITED( status ) )
            {
                return WEXITSTATUS( status ) ;
            }
            else
            {
                printf( "exe: child process failed\n" ) ;
                return 1 ;
            }
        }
    }
    perror( "exe" ) ;
    return 1 ;
}

int main( int argc, char * argv[] )
{
    if( argc != 3 )
    {
        printf( "Usage: exe program /fake/first/program/argument\n" ) ;
        return 1 ;
    }
    return exe( argv[1], argv[2] ) ;
}

现在你可以执行一个传递任意第一个参数的程序,如下所示:

exe program /fake/first/program/argument

用户要求Theo de Raadt实现在此thread

中获取已执行文件的完整路径所需的内容
  

我想我们可以将'path'粘贴到辅助矢量值中并且具有   ld。如果使用$ ORIGIN,还要调用realpath()吗?就是那个或者   让内核存储进程生命周期的整个路径   使用sysctl()获取。现在它只存储最后一个组件   p_comm中的(已解析的)原始路径。

他回答说:

  

相当昂贵,因为这么小的需求。

相关问题