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、範囲外になると、環境にはガベージ ポインターが含まれ、それにアクセスしようとすると、segfault またはガベージが返されます。

于 2011-07-05T23:13:36.083 に答える
1

ギーコサウルスの回答に加えて。シェルからプログラムを実行する場合、たとえば、C++ プログラムから "export TCL_LIBRARY=calculated_value" (使用するシェルによって異なります) のような文字列をファイルに書き込んで、このファイルを実行できます。

#!/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 に答える