21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

value of an environment variable actually changes it. If you use the code from Recipe<br />

1.1, you can be reasonably certain that there is only one environment variable for<br />

each name.<br />

Instead of using putenv( ) to modify the value of an environment variable, use spc_<br />

putenv( ), shown in the following code. It will properly handle an environment as the<br />

code in Recipe 1.1 builds it, as well as an unaltered environment. In addition to modifying<br />

the value of an environment variable, spc_putenv( ) is also capable of adding<br />

new environment variables.<br />

We have not copied putenv( )’s signature with spc_putenv( ). If you use putenv( ),<br />

you must pass it a string of the form “NAME=VALUE”. If you use spc_putenv( ), you<br />

must pass it two strings; the first string is the name of the environment variable to<br />

modify or add, and the second is the value to assign to the environment variable. If<br />

an error occurs, spc_putenv( ) will return –1; otherwise, it will return 0.<br />

Note that the following code is not thread-safe. You need to explicitly avoid the possibility<br />

of manipulating the environment from two separate threads at the same time.<br />

#include <br />

#include <br />

static int spc_environ;<br />

int spc_putenv(const char *name, const char *value) {<br />

int del = 0, envc, i, mod = -1;<br />

char *envptr, **new_environ;<br />

size_t delsz = 0, envsz = 0, namelen, valuelen;<br />

extern char **environ;<br />

/* First compute the amount of memory required for the new environment */<br />

namelen = strlen(name);<br />

valuelen = strlen(value);<br />

for (envc = 0; environ[envc]; envc++) {<br />

if (!strncmp(environ[envc], name, namelen) && environ[envc][namelen] = = '=') {<br />

if (mod = = -1) mod = envc;<br />

else {<br />

del++;<br />

delsz += strlen(environ[envc]) + 1;<br />

}<br />

}<br />

envsz += strlen(environ[envc]) + 1;<br />

}<br />

if (mod = = -1) {<br />

envc++;<br />

envsz += (namelen + valuelen + 1 + 1);<br />

}<br />

envc -= del; /* account for duplicate entries of the same name */<br />

envsz -= delsz;<br />

/* allocate memory for the new environment */<br />

envsz += (sizeof(char *) * (envc + 1));<br />

94 | Chapter 3: Input Validation<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!