How to use setenv() to export a variable in c++?

2019-01-09 09:56发布

I need to export several variables such that they look like the following in the command line

export ROS_HOSTNAME=xxx

How do I use setenv() in c++ to achieve that?

Thanks.

3条回答
ら.Afraid
2楼-- · 2019-01-09 10:01

Do like this:

setenv("ROS_HOSTNAME", "xxx", true);

Note it's synopsis as well:

#include <stdlib.h>

int setenv(const char *envname, const char *envval, int overwrite);

See this link for more details on setenv().

查看更多
看我几分像从前
3楼-- · 2019-01-09 10:03

From the setenv() manual entry:

SYNOPSIS

#include <stdlib.h>  
int setenv(const char *envname, const char *envval, int overwrite);

DESCRIPTION
The setenv() function shall update or add a variable in the environment of the calling process. The envname argument points to a string containing the name of an environment variable to be added or altered. The environment variable shall be set to the value to which envval points. The function shall fail if envname points to a string which contains an '=' character. If the environment variable named by envname already exists and the value of overwrite is non-zero, the function shall return success and the environment shall be updated. If the environment variable named by envname already exists and the value of overwrite is zero, the function shall return success and the environment shall remain unchanged.

If the application modifies environ or the pointers to which it points, the behavior of setenv() is undefined. The setenv() function shall update the list of pointers to which environ points.

The strings described by envname and envval are copied by this function.

The setenv() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

RETURN VALUE
Upon successful completion, zero shall be returned. Otherwise, -1 shall be returned, errno set to indicate the error, and the environment shall be unchanged.

So you should call

setenv("ROS_HOSTNAME","xxx",1); // does overwrite

or

setenv("ROS_HOSTNAME","xxx",0); // does not overwrite

for your case. Depends, if you want to overwrite a possibly existing definition.

NOTE:

You can't use setenv() to export variables from your process to the calling process (shell)! Child processes created with fork, will inherit the current processes environment definitions, thus your changes and additions as well.

查看更多
Anthone
4楼-- · 2019-01-09 10:17

Here the signature for the setenv function

#include <stdlib.h>

int setenv(const char *envname, const char *envval, int overwrite);

Link : http://pubs.opengroup.org/onlinepubs/009695399/functions/setenv.html

In your case you call it like this:

setenv("ROS_HOSTNAME", "xxx", true);

the last boolean argument indicates if you want to overwrite the value of the environment variables if it already exists.

查看更多
登录 后发表回答