#include "stdafx.h"
#include <windows.h>
//枚举所有环境变量
void EnumEnvironment()
{
char *l_EnvStr;
l_EnvStr = GetEnvironmentStrings();
if (l_EnvStr)
{
LPTSTR l_str = l_EnvStr;
int count = 0;
while (true)
{
if (*l_str == 0) break;
while (*l_str != 0) l_str++;
l_str++;
count++;
}
printf("count:%d\n",count);
for (int i = 0; i < count; i++)
{
printf("%s\n", l_EnvStr);
while(*l_EnvStr != '\0')
l_EnvStr++;
l_EnvStr++;
}
FreeEnvironmentStrings(l_EnvStr);
}
}
//读取环境变量值
BOOL ReadUID()
{
char uid[1024]={0};
if (GetEnvironmentVariableA("param_uid",uid,sizeof(uid)))
{
printf("uid:%s\n",uid);
return TRUE;
}else{
printf("获取参数失败\n");
}
return FALSE;
}
typedef struct tagEnvInfo
{
LPSTR lpStr;
DWORD dwSize;
DWORD dwCount;
}EnvInfo;
//获取所有环境变量缓冲区信息
LPSTR GetEnvironmentStringsEx(EnvInfo * pEnvInfo)
{
if (pEnvInfo)
{
pEnvInfo->lpStr=NULL;
pEnvInfo->dwSize=0;
pEnvInfo->dwCount=0;
}
LPSTR lpEnvStr=GetEnvironmentStrings();
if (lpEnvStr)
{
pEnvInfo->lpStr=lpEnvStr;
LPSTR p = lpEnvStr;
while (true)
{
if (*p == 0) break;
while (*p != 0)
{
p++;
if (pEnvInfo) pEnvInfo->dwSize++;
}
p++;
if (pEnvInfo)
{
pEnvInfo->dwSize++;
pEnvInfo->dwCount++;
}
}
return lpEnvStr;
}
return NULL;
}
//在当前环境变量后增加一个自定义的环境变量,返回环境变量字符串
LPSTR NewEnvironment(const char *name, const char *value)
{
LPSTR lpEnvironment=NULL;
EnvInfo env;
LPSTR lpEnvStr=GetEnvironmentStringsEx(&env);
if (lpEnvStr)
{
DWORD dwAllocSize=env.dwSize+strlen(name)+strlen(value)+3;//1个等号,2个空结束符号
lpEnvironment=(LPSTR)GlobalAlloc(0, dwAllocSize);
if (lpEnvironment)
{
memset(lpEnvironment,0,dwAllocSize);
memcpy(lpEnvironment,lpEnvStr,env.dwSize);
sprintf(lpEnvironment+env.dwSize,"%s=%s",name,value);
}
FreeEnvironmentStrings(lpEnvStr);
}
return lpEnvironment;
}
int main(int argc, char* argv[])
{
if (ReadUID()) return 0;
LPSTR lpEnvironment=NewEnvironment("param_uid","yangxiaowei");
STARTUPINFO si;
PROCESS_INFORMATION pi;
memset( &si, 0, sizeof(si) );
memset( &pi, 0, sizeof(pi) );
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow=SW_SHOWNORMAL;
char szBuff[1024]={0};
GetModuleFileName(::GetModuleHandle(NULL), szBuff, sizeof(szBuff));
if (CreateProcess(
NULL, // No module name (use command line).
szBuff, // Command line.
NULL, // Process handle not inheritable.
NULL, // Thread handle not inheritable.
FALSE, // Set handle inheritance to FALSE.
NULL, // No creation flags.
lpEnvironment, // Use parent's environment block.
NULL, // Use parent's starting directory.
&si, // Pointer to STARTUPINFO structure.
&pi )) // Pointer to PROCESS_INFORMATION structure.
{
printf("启动成功\n");
}else{
printf("启动失败\n");
}
if (lpEnvironment) GlobalFree(lpEnvironment);
Sleep(600000);
return 0;
}