0

所以我尝试下一个代码:

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <sstream>
#include <boost/filesystem/v3/path.hpp>
#include <boost/filesystem/v3/operations.hpp>
#ifdef WIN
#include <Windows.h>
#endif

void setEnviromentVariable(std::string name, boost::filesystem::path value)
{
    if ( getenv (name.c_str())==NULL)
    {
        std::cout << "Hit ENTER to restart application in order to agree with the next terms of use: do not eat my bytes!)" << std::endl;
        std::stringstream VAR;
        VAR << name<< "=" << value.native().c_str();
           #ifdef WIN
        std::stringstream VAL;
        VAL << value.native().c_str();
        if( !SetEnvironmentVariable(TEXT(name.c_str()), TEXT(VAL.str().c_str()))) 
        {
            printf("SetEnvironmentVariable failed (%d)\n", GetLastError()); 
        }
          #else
        setenv(VAR.str().c_str());
          #endif
        std::cin.get();

    }

}
int main(int argc, char *argv[])
{
        boost::filesystem::path full_path( boost::filesystem::current_path() / "assets/" );
        setEnviromentVariable("TCL_LIBRARY", full_path);
}

我的代码有什么问题?为什么它没有设置任何环境变量,为什么它没有显示任何错误?(WIN代码就是以此为基础的。

4

3 回答 3

2

putenv()将指定的字符串指针放在环境向量中;它不会复制字符串值。

string becomes部分环境指向的字符串。程序不应更改或释放字符串,也不应使用堆栈或其他瞬态字符串变量作为putenv().

因此,当VAR超出范围时,环境包含一个垃圾指针,尝试访问它会出现段错误或返回垃圾。

于 2011-07-05T23:13:36.083 回答
1

除了geekosaur的答案。如果你从 shell 运行程序,那么你可以,例如,从你的 C++ 程序中写一个字符串,如“export TCL_LIBRARY=calculated_value”(取决于你使用什么 shell)到某个文件,然后执行这个文件。

#!/bin/bash
your_program.exe
source generated_file_with_variable
next_program.exe
于 2011-07-05T23:32:09.690 回答
0

您的流程有自己的环境副本,您的所有更改都会影响该副本。唯一会看到您的修改的其他程序是您启动的子进程,当您生成子进程时,它们会及时看到您的环境冻结。启动您的程序将完全不受影响。

因此,您关于重新启动应用程序的评论毫无意义。新实例将获得父进程环境的副本,而不是您一直在对其进行更改的环境。(OTOH,如果您的程序启动了新副本,它将继承您更改的环境块。)

于 2011-07-05T23:59:45.427 回答