如何使用平台无关的方法在C中获取执行程序的目录? [英] How do I get the executing program's directory in C using a plataform independent method?

查看:57
本文介绍了如何使用平台无关的方法在C中获取执行程序的目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Linux上同时针对unix和win32(在每个构建中交叉编译)平台开发了我的应用程序,因此随时可用的功能就不错了:).我正在使用具有 gchar * g_get_current_dir(void)函数的glib,它返回当前目录,但是我真正需要的是可执行文件的目录.我没有C编程经验,所以欢迎您提出任何建议.

I develop my app in Linux for both unix and win32(cross compile at each build) platforms, so a ready to use function would be nice :). I'm using glib that has the gchar* g_get_current_dir(void) function and it returns the current directory, but what I really need is the executable's directory. I'm inexperienced in C programming so any suggestions are welcome.

推荐答案

在Unix下,例如具有/proc 目录的操作系统,您可以 readlink /proc/self/exe 获取实际的可执行文件的完整路径,即使 argv [0] 没有该路径也是如此.

Under Unix like operating systems that have the /proc directory you can readlink /proc/self/exe to get the actual executable files full path even when argv[0] does not have this.

但是,如果可执行文件是使用 fexecv (在许多系统上不可用)启动的,并且在系统上作为系统调用实现的,则这可能不起作用. fexecv 类似于 execve ,不同之处在于,它传递了打开文件描述符而不是文件名来运行.在Linux下,它是通过对`"/proc/self/%i",fd生成的字符串调用 execve 来实现的,因此该文件必须在程序运行时位于文件系统中.开始了.

This may not work, however, if the executable was started with fexecv (not available on many systems) and if that is implemented as a system call on your system. fexecv is just like execve except that it is passed an open file descriptor rather than a filename to run. Under Linux it is implemented by calling execve on the string generated by `"/proc/self/%i", fd", so the file would have to live in the file system at the time the program was started.

我认为GNU/Hurd本机支持 fexecve .

I think that GNU/Hurd supports fexecve natively.

可执行文件在执行后可能会被重命名或从文件系统取消链接,这使它成为未命名的文件,一旦停止打开该文件就会消失(在这种情况下,通常运行文件)要求它由内核打开).

It is possible for an executable file to be renamed or unlinked from the filesystem after it has been executed which makes it become an unnamed file which will go away as soon as it ceases to be open (in this context running a file usually requires it to be open by the kernel).

这篇关于如何使用平台无关的方法在C中获取执行程序的目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆