E-MailRelay
genvironment_unix.cpp
Go to the documentation of this file.
1//
2// Copyright (C) 2001-2021 Graeme Walker <graeme_walker@users.sourceforge.net>
3//
4// This program is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// This program is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with this program. If not, see <http://www.gnu.org/licenses/>.
16// ===
17///
18/// \file genvironment_unix.cpp
19///
20
21#include "gdef.h"
22#include "genvironment.h"
23#include <cstdlib> // std::getenv()
24#include <cstring>
25#include <stdexcept>
26
27std::string G::Environment::get( const std::string & name , const std::string & default_ )
28{
29 const char * p = std::getenv( name.c_str() ) ;
30 return p ? std::string(p) : default_ ;
31}
32
33char * G::Environment::stringdup( const std::string & s )
34{
35 void * p = std::memcpy( new char[s.size()+1U] , s.c_str() , s.size()+1U ) ; // NOLINT
36 return static_cast<char*>(p) ;
37}
38
39void G::Environment::put( const std::string & name , const std::string & value )
40{
41 // see man putenv(3) NOTES
42 char * deliberately_leaky_copy = stringdup( std::string().append(name).append(1U,'=').append(value) ) ; // NOLINT
43 ::putenv( deliberately_leaky_copy ) ;
44} // NOLINT
45
47{
48 Environment env ;
49 env.add( "PATH" , "/usr/bin:/bin" ) ; // no "."
50 env.add( "IFS" , " \t\n" ) ;
51 return env ;
52}
53
Holds a set of environment variables and also provides static methods to wrap getenv() and putenv().
Definition: genvironment.h:39
static void put(const std::string &name, const std::string &value)
Sets the environment variable value.
static std::string get(const std::string &name, const std::string &default_)
Returns the environment variable value or the given default.
static Environment minimal()
Returns a minimal, safe set of environment variables.
void add(const std::string &name, const std::string &value)
Adds a variable to this set.