I'm trying to make a program that a bash script runs. I want the bash script to be able to change the state of the c++ program, and the only thing I could find was to use environment variables. Thing is, its seems getenv only gets the value at the time when the program was run.
Bash
export BLINK=1
./blink &
sleep 5s
unset BLINK
C++
int main(int args, char **argv) {
char *blink = getenv("BLINK");
while(blink && blink[0] == '1')
{
std::cout << getenv("BLINK") << std::endl;
usleep(500000);
}
return 1;
}
So what this does is run the blink program, wait 5 seconds then unset the environment. The C++ program however always sees the enviorment value as 1 and never stops. How do I get an updated environment variable while the program is running? Or is there a better way to have a bash script control the state of a c++ program.
EDIT I should note, I do not want to just kill the process either because it has to turn off hardware when it ends.
It is not possible to modify program environment after it is started. You have to use another method of interprocess communication. The simplest one is to register handler for some signal to your app (e.g. SIGUSR1), and then send it using
kill -SIGUSR1 <pid>
command.There are also other solutions available, e.g. create named pipe (using
pipe
shell command), and check periodically if someone wrote something to it. If yes, exit loop.You can also use sockets if you want, but this could be more complicated.