Link to home
Start Free TrialLog in
Avatar of learningunix
learningunix

asked on

variable

i am calling getenv() in my C++ code

If I call C++ executable directly then getenv() it reads the value correctly

However if I call the executable from within /etc/init.d/myDaemon  
"myDaemon "  then calls C++ executable, in this case getenv() does not read the value.
I have to manually set the env variable in /etc/init.d/my.exe in order my C++ executable to read it.

not sure why it behaves this way

ASKER CERTIFIED SOLUTION
Avatar of parnasso
parnasso
Flag of Italy image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jkr
How are you starting the executable that calls 'getenv()'? if you are using 'system()', this call will start a new shell and tyour changes to the environment are null and void, meaning the process won't find the environment variable you have set before:
NAME
     system -- pass a command to the shell

LIBRARY
     Standard C Library (libc, -lc)

SYNOPSIS
     #include <stdlib.h>

     int
     system(const char *string);

DESCRIPTION
     The system() function hands the argument string to the command inter-
     preter sh(1).  The calling process waits for the shell to finish execut-
     ing the command, ignoring SIGINT and SIGQUIT, and blocking SIGCHLD.

     If string is a NULL pointer, system() will return non-zero if the command
     interpreter sh(1) is available, and zero if it is not.

Open in new window


You should rather use one of the 'exec*()' functions, i.e.
void run_progrem(const char* pCmd) {

  /* Fork a child */

  if ((pid = fork()) == 0) {

      /* If execl() returns at all, there was an error. */

      if (execlp(pCmd, pCmd, NULL)) { /* Bye bye! */
        perror("execl");
        exit(128);
      }
    }
}

Open in new window

Avatar of learningunix
learningunix

ASKER

can i set that env variable in bash script ?
export VAR=<value>

how to read the value in bash script?
In the myDaemon bash script if I do
echo $VAR

it did not print anything. meaning the bash script is somehow not  able to read the env variable
You can do that in a bash script, sure - but this variable will only be valid in the same "shell", as soon as you start another one that is unrelated to the one you use 'export', the change will be lost.
thx