gfbio
gfbio

Reputation: 1546

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.

Upvotes: 2

Views: 148

Answers (4)

Eric
Eric

Reputation: 11

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.

Upvotes: 0

nategoose
nategoose

Reputation: 12382

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.

Upvotes: 6

tristan
tristan

Reputation: 4322

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

Upvotes: -1

Johan
Johan

Reputation: 5053

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]);
}

Upvotes: 0

Related Questions