konradk
konradk

Reputation: 193

Add executable to PATH at run time

My goal is to add a program path to PATH variable so a different part of program can launch it by merely specifying its name, like this

int main()
{
    system("export PATH=%PATH%;/home/user/Workspace/myproject/build/bin/mybinary");
    system("echo $PATH");// <-- the PATH is changed

    //a far place in code
    system("mybinary"); // <-- this should run the executable, but it can't find it
    return 0;
}

Is this even possible to be done?

Upvotes: 1

Views: 381

Answers (1)

sosensio
sosensio

Reputation: 39

In Linux, you can use setenv() and getenv() to achieve it, included in the standard library. An example would be:

int main () {
    char *path;
    
    path = getenv("PATH"); /* Gets current value of PATH */
    strcat(path, ":/path/to/binary"); /* Adds the new path at the end */
    
    if(setenv("PATH", path, 1)) { /* Override allowed as 3rd parameter is nonzero */
        /* Handle error */
    }
}

Note: as said in this post setenv() can't export variables to the calling process, only to itself and any new child created with fork().

Upvotes: 2

Related Questions