如何使用 setenv() 在 C++ 中导出变量? [英] How to use setenv() to export a variable in c++?

查看:86
本文介绍了如何使用 setenv() 在 C++ 中导出变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要导出几个变量,使它们在命令行中如下所示

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

export ROS_HOSTNAME=xxx

我如何在 C++ 中使用 setenv() 来实现这一点?

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

谢谢.

推荐答案

来自 setenv() 手册条目:

概要

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

描述
setenv() 函数应在调用进程的环境中更新或添加变量.envname 参数指向一个包含环境变量名称的字符串被添加或更改.环境变量应设置为 envval 指向的值.如果 envname 指向包含="字符的字符串,则该函数将失败.如果由envname命名的环境变量已经存在,overwrite的值不为零,函数返回成功,更新环境.如果环境由envname命名的变量已经存在,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.

如果应用程序修改了环境或它指向的指针,则 setenv() 的行为是未定义的.setenv() 函数应更新指向哪个环境的指针列表点.

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.

envname 和 envval 描述的字符串被这个函数复制.

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

setenv() 函数不需要可重入.不需要可重入的函数不需要是线程安全的.

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

返回值
成功完成后,应返回零.否则返回-1,设置errno表示错误,环境不变.

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.

所以你应该打电话

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

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

对于你的情况.视情况而定,如果您想覆盖可能存在的定义.

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

注意:

您不能使用 setenv() 将变量从您的进程导出到调用进程(shell)!使用 fork 创建的子进程将继承当前的进程环境定义,以及您的更改和添加.

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.

这篇关于如何使用 setenv() 在 C++ 中导出变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆