Question

hello I’m trying to execute a bash file which has export inside, and this into my Cpp program.

The goal is to set my needed environment variable automatically at the start of one of my program.

I can't seem to make it work.

piece of my myExport.sh:

export LOG4CXXCONFFILE="/home/me/workspace/Log/log4cxx.properties"

my code is :

#include <stdlib.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    qDebug() << system(" bash myExport.sh");
    try
    {
        QString myFile = getenv("LOG4CXXCONFFILE");
        qDebug() << "my env variable directory path:"<< myFile;
    }
    catch(Exception&)
    {
        result = "EXIT_FAILURE";
    }
return a.exec();
}

my debug show me it worked but I can't get the env. variable:

0
my env variable directory path: ""

I thought it was maybe becauseThe scripts only sets the environment inside the subshell it runs in, so i tried:

qDebug() << system(". ./myExport.sh");

which got me the same answer.

so I also tried :

qDebug() << system("source myExport.sh");

and the answer was:

sh: 1: source: not found
32512 
my env variable directory path: ""

i tryied :

qDebug() << system("bash source myExport.sh");
bash: source: Aucun fichier ou dossier de ce type   (no file or directory of this type, don't know why this is the only error in french)
32512 
my env variable directory path: ""

I'm running out of idea, anybody know why it's not working please?

Was it helpful?

Solution

I can't say I fully understand your question, but it seems to me that you're trying to update the environment of your process through a bash script. That's simply not possible. A child process can never modify the environment of its parent process.

And your application's process is not bash (it's your application), so it cannot "source" a shell script. If you have an environment-setup bash script, you have these options:

  1. Run the env-setup script before you launch your application (perhaps launching your application through a wrapper bash script).

  2. Execute bash as a child process, have it source the script and retrieve the relevant info out from it (such as writing the environment to standard output in the bash script and capturing its standard output in C++). For this, you might want to look at QProcess, especially at QProcess::setReadChannel().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top