Environment Variables in Cilk

Environment variables are a universal mechanism for conveying configuration information to Unix programs. Let’s look at how to set, get, and list environment variables in Cilk.

#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
#include <cilk/cilk.h>

int main() {
    // To set a key/value pair, use setenv. To get a
    // value for a key, use getenv. This will return
    // NULL if the key isn't present in the environment.
    setenv("FOO", "1", 1);
    std::cout << "FOO: " << (getenv("FOO") ? getenv("FOO") : "") << std::endl;
    std::cout << "BAR: " << (getenv("BAR") ? getenv("BAR") : "") << std::endl;

    // Use environ to list all key/value pairs in the
    // environment. This is an array of strings in the
    // form KEY=value. You can iterate through it to
    // get all the keys. Here we print all the keys.
    std::cout << std::endl;
    for (char **env = environ; *env != nullptr; ++env) {
        std::string pair = *env;
        size_t pos = pair.find('=');
        if (pos != std::string::npos) {
            std::cout << pair.substr(0, pos) << std::endl;
        }
    }

    return 0;
}

Running the program shows that we pick up the value for FOO that we set in the program, but that BAR is empty.

$ g++ -fcilkplus environment_variables.cpp -o environment_variables
$ ./environment_variables
FOO: 1
BAR: 

TERM_PROGRAM
PATH
SHELL
...
FOO

The list of keys in the environment will depend on your particular machine.

If we set BAR in the environment first, the running program picks that value up.

$ BAR=2 ./environment_variables
FOO: 1
BAR: 2
...

Note that Cilk, being an extension of C++, uses C++ standard library functions for environment variable operations. The setenv and getenv functions are part of the C standard library, which is accessible in C++. The environ variable is also a C feature that’s available in C++.

Also, Cilk doesn’t provide any specific features for handling environment variables beyond what C++ offers. The parallel programming features of Cilk are not directly applicable to this example, but could be used if you needed to process environment variables in parallel.