gpt4 book ai didi

c++ - 如何使用 setenv() 在 C++ 中导出变量?

转载 作者:IT老高 更新时间:2023-10-28 22:19:42 32 4
gpt4 key购买 nike

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

export ROS_HOSTNAME=xxx

如何在 c++ 中使用 setenv() 来实现?

谢谢。

最佳答案

setenv() 手动输入:

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.

所以你应该调用

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

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

针对您的情况。取决于,如果你想覆盖一个可能存在的定义。

注意:

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

关于c++ - 如何使用 setenv() 在 C++ 中导出变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17929414/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com