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

﹥>﹥吖頭↗ 提交于 2019-11-27 08:53:45

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.

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.

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().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!