c-在运行时将可执行文件添加到PATH



我的目标是向path变量添加一个程序路径,这样程序的不同部分就可以通过指定其名称来启动它,比如这个

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

这样做可能吗?

在Linux中,您可以使用标准库中包含的setenv()getenv()来实现它。例如:

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 */
}
}

注意:如本文所述,setenv()不能将变量导出到调用进程,只能导出到它自己和用fork()创建的任何新子进程。

最新更新