开发者

Get startup position

i need to find the startup position of a script in C. I must check if my script has been launched from /usr/bin or from another directory. I've tried with get_current_directory_name() but it returns the current path where I was browsing when i launched the script, so if I do: cd /home/myaccount/ && my-开发者_如何转开发script it returns /home/myaccount, but what i need is the startup position.


readlink("/proc/self/exe", buffer, buffer_size)

This will get you the location of the executable under Linux. man 2 readlink

If you are not using Linux you can try examining argv[0] and see if that is the location of the currently running program, but it is entirely possible to run a program with a different argv[0] than the path to the program; it could be either the executable name, relative path, or even something that has nothing at all to do with the program being run.

A last effort to determine this could be to search for the program in the PATH, and assume that if it is there then that was how it was run. I wouldn't trust this very much, though.

The best solution is to not write a program that relies on this type of information.


Well, cd /home/myaccount will change the current directory before my-script is launched, which means that my-script will not know where it originally was. Maybe you can look at the OLDPWD environment variable, but that will not tell you if you switched dir just before you ran my-script or a long time before that.

Or maybe I misunderstood you. Maybe you are looking for argv[0]?

int main(int argc, char *argv[]) {
  printf("%s\n", argv[0]);
}


Fabio,

If you run a 'C script' then you have a process which has executed (interpreted or compiled on-the-fly) this .c source code file.

When you will try to identify the 'starting point or origin of the script' you will find the parent process path and name.

There is no way to execute a C script from the position of its source code file - unless the parent process is actually compiling the C source code file into an executable file (which can then be stored at any place where the parent process has access).

Hope is clarrifies this issue.


besides argv[0], you can try getcwd() to get the path

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜