[Unix]在程序中取得当前程序可执行文件的路径
出乎意料,这个貌似简单的问题麻烦的紧,在Unix下没有通用且简单的方法解决。stackoverflow上有人问了这个问题:
http://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe
简单但平台相关的方法(stackoverflow上的回答):
-
Mac OS X:
_NSGetExecutablePath()
(man 3 dyld) -
Linux:
readlink /proc/self/exe
-
Solaris:
getexecname()
-
FreeBSD:
sysctl CTL_KERN KERN_PROC KERN_PROC_PATHNAME -1
-
BSD with procfs:
readlink /proc/curproc/file
-
Windows:
GetModuleFileName()
withhModule
=NULL
HP的一个页面上有一个通用的方法: http://h21007.www2.hp.com/portal/site/dspp/menuitem.863c3e4cbcdc3f3515b49c108973a801?ciid=88086d6e1de021106d6e1de02110275d6e10RCRD 程序挺长,方法是根据argv[0]来判断是由绝对/相对路径执行的当前程序还是通过$PATH的方式执行的。对于后一种执行方式,通过在$PATH中依次查找的方式找到具体的路径。
想来想去,我也没想到更好的方法。对于上面那个通用的方法,到$PATH中查找的过程可以改为通过popen调用which的方式简化一些。
PS:有意思的是,搜索的时候发现不管是中文页面还是英文页面,都有不少语文不好的同学建议使用getcwd()...
2022年1月26日 00:03
Ever since the locations are clear (or maybe nearly clear), it’s the perfect time to make your home or residence look more desirable than the item did when you initially moved with. Many residence and household contracts call for a “broom-clean” while other people call for a detailed guidelines that covers many techniques from the stove towards baseboards.
2023年2月04日 04:56
To get the path of the current program executable file in a program, you can use the sys module in Python. The cbd benefits above thread will give more details regarding that and the step-by-step procedure is discussed here. I am looking here to more updates regarding that and keep sharing more details here.