修改环境变量(GetEnvironmentVariable、SetEnvironmentVariable、GetEnvironmentStrings)

Each process has an environment block associated with it.The environment block consists of a null-terminated block

of null-teminated strings (meaning there are two bytes at the end of the block),where each string is in the form:

name = value

All strings in the environment block must be sorted alphabetically by name. The sort is case-insensitive,

Unicode order, without regard to locale. Because the equal sign is a separator, it must not be used in the name of an 

environment variable.

Example 1

By default, a child process inherits a copy of the environment block of the parent process. The following example demonstrates

how to create a new environment block to pass to a child process using CreateProcess.

This example uses the code in example three as the child process, Ex3.exe.

#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <strsafe.h>

#define BUFSIZE 4096

int _tmain() 
{
    TCHAR chNewEnv[BUFSIZE];
    LPTSTR lpszCurrentVariable;
    DWORD dwFlags=0;
    TCHAR szAppName[] = TEXT("ex3.exe");
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    BOOL fSuccess;

    //Copy environment strings into an environment block
    
    lpszCurrentVariable = (LPTSTR) chNewEnv;
    if (FAILED(StringCchCopy(lpszCurrentVariable, BUFSIZE, TEXT("MySetting=A")))) {
        printf("String copy failed\n");
        return FALSE;
    }
    lpszCurrentVariable += lstrlen(lpszCurrentVariable) + 1;
    if (FAILED(StringCchCopy(lpszCurrentVariable, BUFSIZE, TEXT("MyVersion=2")))) {
        printf("String copy failed\n");
        return FALSE;
    }

    //Terminate the block with a NULL byte.
    lpszCurrentVariable += lstrlen(lpszCurrentVariable) + 1;
    *lpszCurrentVariable = (TCHAR)0;
    
    //Create the child process, specifying a new environment block
    SecureZeroMemory(&si, sizeof(STARTUPINFO));
    si.cb = sizeof(STARTUPINFO);
    
#ifdef UNICODE
    dwFlags = CREATE_UNICODE_ENVIRONMENT;
#endif
    fSuccess = CreateProcess(szAppName, NULL, NULL, NULL, TRUE, dwFlags, 
                (LPVOID)chNewEnv, //new environment block
                NULL, &si, &pi);
    if (!fSuccess) {
        printf("CreateProcess failed(%d)\n", GetLastError());
        return FALSE;
    }
    WaitForSingleObject(pi.hProcess, INFINITE);
    return TRUE;
}

 

Example 2

Altering the environment variables of a child process during process creation is the only way one process can directly change

the environment variables of another process. A process can never directly change the environment variables

of another process that is not a child of that process.

If you want the child process to inherit most of the parent's environment with only a few changes, retrieve the 

current values using GetEnvironmentVariable, save these values, create an updated block for the child process

to inherit, create the child process, and the restore the saved values using SetEnvironmentVariable, as shown in 

the following example.

This example uses the code in example three as the child process, Ex3.exe.

#include <windows.h>
#include <tchar.h>
#include <stdio.h>

#define BUFSIZE 4096
#define VARNAME TEXT("MyVariable")

int _tmain() 
{
    DWORD dwRet, dwErr;
    LPTSTR pszOldVal;
    TCHAR szAppName[] = TEXT("ex3.exe");
    DWORD dwFlags = 0;
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    BOOL fExist, fSuccess;

    // Retrieves the current value of the variable if it exists.
    // Sets the variable to a new value, creates a child process,
    // then uses SetEnvironmentVariable to restore the original 
    // value or delete it if it did not exist previously.
    
    pszOldVal = (LPTSTR) malloc(BUFSIZE * sizeof(TCHAR));
    if (NULL == pszOldVal) {
        printf("Out of memory\n");
        return FALSE;
    }
    
    dwRet = GetEnvironmentVariable(VARNAME, pszOldVal, BUFSIZE);
    if (0 == dwRet) {
        dwErr = GetLastError();
        if (ERROR_ENVVAR_NOT_FOUND == dwErr) {
            printf("Environment variable does not exist.\n");
            fExist = FALSE;
        }
    } else if (BUFSIZE < dwRet) {
        pszOldVal = (LPTSTR) realloc(pszOldVal, dwRet *sizeof(TCHAR));
        if (NULL == pszOldVal) {
            printf("Out of memory!\n");
            return FALSE;
        }
        dwRet = GetEnvironmentVariable(VARNAME, pszOldVal, dwRet);
        if (!dwRet) {
            printf("GetEnvironmentVariable failed(%d)\n", GetLastError());
            return FALSE;
        } else {
            fExist = TRUE;
        }
    } else {
        fExist = TRUE;
    }
    // Set a value for the child process to inherit. 
 
    if (! SetEnvironmentVariable(VARNAME, TEXT("Test"))) 
    {
        printf("SetEnvironmentVariable failed (%d)\n", GetLastError()); 
        return FALSE;
    }
 
    // Create a child process. 

    SecureZeroMemory(&si, sizeof(STARTUPINFO));
    si.cb = sizeof(STARTUPINFO);
 
#ifdef UNICODE
    dwFlags = CREATE_UNICODE_ENVIRONMENT;
#endif

    fSuccess = CreateProcess(szAppName, NULL, NULL, NULL, TRUE, dwFlags, 
        NULL,     // inherit parent's environment 
        NULL, &si, &pi); 
    if (! fSuccess) 
    {
        printf("CreateProcess failed (%d)\n", GetLastError()); 
    }
    WaitForSingleObject(pi.hProcess, INFINITE);

    // Restore the original environment variable. 
 
    if(fExist)
    {
        if (! SetEnvironmentVariable(VARNAME, pszOldVal)) 
        {
            printf("SetEnvironmentVariable failed (%d)\n", GetLastError()); 
            return FALSE;
        }
    }
    else SetEnvironmentVariable(VARNAME, NULL);

    free(pszOldVal);
    
    return fSuccess;
}

Example 3

The following example retrieves the process's environment block using GetEnvironmentStrings and prints the contents to the console.

#include <windows.h>
#include <tchar.h>
#include <stdio.h>

int _tmain()
{
    LPTSTR lpszVariable;
    LPTCH lpvEnv;

    //Get a pointer to the environment block.
    lpvEnv = GetEnvironmentStrings();

    //If the returned pointer is NULL, exit.
    if (lpvEnv == NULL) {
        printf("GetEnvironmentStrings failed(%d)\n", GetLastError());
        return 0;
    }
    
    //Variable strings are separated by NULL byte, and the block is 
    //terminated by a NULL byte.
    lpszVariable = (LPTSTR) lpvEnv;
    
    while (*lpszVariable) {
        _tprintf(TEXT("%s\n"), lpszVariable);
        lpszVariable += lstrlen(lpszVariable) + 1;
    }
    FreeEnvironmentStrings(lpvEnv);

    return 1;
}

 

转自:https://blog.csdn.net/xiaoyafang123/article/details/53514866

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值