17.1.1.  Processes and Environment

[ fromfile: environment.xml id: environment ]

  1. PATH, a list of directories to search for executables (also DLLs on windows).

  2. HOME, the location of your home directory.

  3. CPPLIBS, where the C++ Libraries from this book's source examples are installed.

  4. HOSTNAME (*nix) or COMPUTERNAME (win32), which usually gives you the name of your machine.

  5. USER (*nix) or USERNAME (Win32), which usually gives you the currently logged in user id.

Operating system shells enable the user to set environment variables for a process and its future children. Here are some examples.

Figure 17.3.  KDE/Linux process hierarchy

KDE/Linux process hierarchy

Example 17.5. src/environment/setenv.cpp

#include <QCoreApplication>
#include <QTextStream>
#include <QProcess>
#include <QCoreApplication>
#include <QTextStream>
#include <QStringList>
#include <cstdlib>

class Fork : public QProcess {
    public:
    Fork(QStringList argv = QStringList() ) {
        execute("environment", argv); 1
    }
    ~Fork() {
        waitForFinished();
    }
};

QTextStream cout(stdout);
int main(int argc, char* argv[]) {

    QCoreApplication qca(argc, argv);
    QStringList al = qca.arguments();
    al.removeAt(0);
    bool fork=al.contains("-f");
    if(fork) {
       int i = al.indexOf("-f");
       al.removeAt(i);
    }

    QStringList extraVars;
    if (al.count()  > 0) {
        setenv("PENGUIN", al.first().toAscii(), true);
    }
    cout << " HOME=" << getenv("HOME") << endl;
    cout << " PWD=" << getenv("PWD") << endl;
    cout << " PENGUIN=" << getenv("PENGUIN") << endl;
    
    if (fork) {
        Fork f;   
    }
}

1

Runs this same app as a child.


src/environment> export PENGUIN=tux
src/environment> ./environment -f
HOME=/home/lazarus
PWD=src/environment
PENGUIN=tux
HOME=/home/lazarus
PWD=src/environment
PENGUIN=tux
src/environment> ./environment -f opus
HOME=/home/lazarus
PWD=src/environment
PENGUIN=opus
HOME=/home/lazarus
PWD=src/environment
PENGUIN=opus
src/environment> echo $PENGUIN
tux
src/environment>