I'm writing a C program on Linux and need to execute a command with system()
, and need to set an environment variable when executing that command, but I don't know how to set the env var when using system()
.
Asked
Active
Viewed 1.8k times
5

John Kugelman
- 349,597
- 67
- 533
- 578

Wang Tuma
- 893
- 5
- 14
- 24
-
*system("var=val cmd")* doesn't that work? – tuxuday Apr 17 '14 at 08:58
-
The argument to `system` is just a shell command line. So you set it the same way you would in the shell. – Barmar Apr 17 '14 at 09:01
-
$ EXAMPLE=test env|grep EXAMPLE --> EXAMPLE=test --> This seems to work in shell... – nikpel7 Apr 17 '14 at 09:20
3 Answers
5
If you want to pass an environment variable to your child process that is different from the parent, you can use a combination of getenv
and setenv
. Say, you want to pass a different PATH
to your child:
#include <stdlib.h>
#include <string.h>
int main() {
char *oldenv = strdup(getenv("PATH")); // Make a copy of your PATH
setenv("PATH", "hello", 1); // Overwrite it
system("echo $PATH"); // Outputs "hello"
setenv("PATH", oldenv, 1); // Restore old PATH
free(oldenv); // Don't forget to free!
system("echo $PATH"); // Outputs your actual PATH
}
Otherwise, if you're just creating a new environment variable, you can use a combination of setenv
and unsetenv
, like this:
int main() {
setenv("SOMEVAR", "hello", 1); // Create environment variable
system("echo $SOMEVAR"); // Outputs "hello"
unsetenv("SOMEVAR"); // Clear that variable (optional)
}
And don't forget to check for error codes, of course.

user703016
- 37,307
- 8
- 87
- 112
2
Use setenv()
api for setting environment variables in Linux
#include <stdlib.h>
int setenv(const char *envname, const char *envval, int overwrite);
Refer to http://www.manpagez.com/man/3/setenv/ for more information.
After setting environment variables using setenv()
use system()
to execute any command.

Alexis Wilke
- 19,179
- 10
- 84
- 156

Rahul R Dhobi
- 5,668
- 1
- 29
- 38
1
This should work:
#include "stdio.h"
int main()
{
system("EXAMPLE=test env|grep EXAMPLE");
}
outputs
EXAMPLE=test

nikpel7
- 656
- 4
- 11
-
1I like this method as it does not spoil the existing environment in the parent (i.e. if you call `system()` multiple times, you may want to define various variables but may not to see the variables you defined for a given call in the other calls!) – Alexis Wilke Jul 18 '16 at 18:34
-