How to `export PATH` from C [closed]

Wondering how to accomplish one of these things from C, so that it persists like it would from ~/.bashrc or ~/.bash_profile:

export PATH=~/bin:$PATH
export PS1="$ "

Wondering if I should use the execl command sort of like this:

#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
int main (void) { return execl("/bin/export", "...", NULL);
}

Or if there is another idiomatic C way to accomplish this properly.

1 Answer

You can't export variables from a program to the parent shell, because it is not possible to modify the environment of another process.

If you want to set up a child process, see man setenv or man execve.

Edit

The difference is that .bashrc is executed by the shell itself, not by a subprocess of the shell. As it is executed by the shell, it can modify the environment of the shell.

The only way around this is to create commands that will be executed by the shell:

main ()
{ printf ("PATH=/dir\n");
}

Then in the Shell execute the output from that command:

$(./myenv)

Or

./myenv > /tmp/file
source /tmp/file

But it is still the shell that modifies its own environment, it just does so by executing commands that are generated from some program.

7

You Might Also Like