How to get the absolute path of an executable at runtime

Is there a way to find at runtime, the absolute path of the executable?

I have some .so libraries together with my application in the same folder, but unfortunately the command ‘dlopen’ doesn’t work with relative path but works only if i give the full path. I don’t know why this is happening.

Thanks in advanced.

Hi Helios,

Is there a way to find at runtime, the absolute path of the executable?

‘getcwd’ will get you the current working directory. Though, this may or may not be where your program is located.

‘call get_command_argument(0,exename)’ will get you the name of the exe, but if you run it locally, it wont give you the full path the the exe (unless the exe is invoked with the full path).

Perhaps, we can combine the two?

:/tmp/args$ cat test.f90 

program test

   character*80 :: me, mydir 
   integer :: scanVal
   logical :: back=.true.
   call get_command_argument(0,me)
   scanVal = scan (me, '/', back)
   if (scanVal .gt. 0) then
       mydir=me(1:scanVal)
   else 
       call getcwd(mydir)   
   endif
   print *, me, mydir

end program test
/tmp/args$ pgf90 test.f90 -o testargs.out
/tmp/args$ testargs.out 
 testargs.out                                                                    
 /tmp/args                                                                       
$ /tmp/args/testargs.out 
 /tmp/args/testargs.out                                                          
 /tmp/args/                                                                      
$ ../args/testargs.out 
 ../args/testargs.out                                                            
 ../args/

If you’re using C, then getcwd is the same but use ‘argv[0]’ for the exe name.

I have some .so libraries together with my application in the same folder, but unfortunately the command ‘dlopen’ doesn’t work with relative path but works only if i give the full path. I don’t know why this is happening.

dlopen searches the paths included in the “LD_LIBRARY_PATH” environment variable. Try setting “LD_LIBRARY_PATH” to the path where your shared libraries are located.

Hope this helps,
Mat