简体   繁体   中英

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?

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM