int usb_install_needs_restart_np(void) { HDEVINFO dev_info; SP_DEVINFO_DATA dev_info_data; int dev_index = 0; SP_DEVINSTALL_PARAMS install_params; int ret = FALSE; dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA); dev_info = SetupDiGetClassDevs(NULL, NULL, NULL, DIGCF_ALLCLASSES | DIGCF_PRESENT); SetEnvironmentVariable("LIBUSB_NEEDS_REBOOT", "1"); if(dev_info == INVALID_HANDLE_VALUE) { usb_error("usb_install_needs_restart_np(): getting " "device info set failed"); return ret; } while(SetupDiEnumDeviceInfo(dev_info, dev_index, &dev_info_data)) { memset(&install_params, 0, sizeof(SP_PROPCHANGE_PARAMS)); install_params.cbSize = sizeof(SP_DEVINSTALL_PARAMS); if(SetupDiGetDeviceInstallParams(dev_info, &dev_info_data, &install_params)) { if(install_params.Flags & (DI_NEEDRESTART | DI_NEEDREBOOT)) { usb_message("usb_install_needs_restart_np(): restart needed"); ret = TRUE; } } dev_index++; } SetupDiDestroyDeviceInfoList(dev_info); return ret; }
int __cdecl main(int argc, char *argv[]) { /* Define some buffers needed for the function */ WCHAR * pResultBuffer = NULL; WCHAR SomeEnvironmentVariable[] = {'P','A','L','T','E','S','T','\0'}; WCHAR TheEnvironmentValue[] = {'T','E','S','T','\0'}; int size; /* * Initialize the PAL and return FAILURE if this fails */ if(0 != (PAL_Initialize(argc, argv))) { return FAIL; } SetEnvironmentVariable(SomeEnvironmentVariable, TheEnvironmentValue); /* Normal case, PATH should fit into this buffer */ size = GetEnvironmentVariable(convert("PALTEST"), // Variable Name pResultBuffer, // Buffer for Value 0); // Buffer size pResultBuffer = malloc(size*sizeof(WCHAR)); GetEnvironmentVariable(convert("PALTEST"), pResultBuffer, size); if(wcsncmp(pResultBuffer,convert("TEST"),wcslen(pResultBuffer) * 2) != 0) { Fail("ERROR: The value in the buffer should have been 'TEST' but was " "really '%s'.",convertC(pResultBuffer)); } free(pResultBuffer); PAL_Terminate(); return PASS; }
// Obtain the right savegame paths for the platform // XP is "%USERPROFILE%\My Documents\My Games" // Vista and up : "%USERPROFILE%\Saved Games" void defineSystemDirectories(const char * argv0) { ARX_UNUSED(argv0); std::string strPath; DWORD winver = GetVersion(); // Vista and up if((DWORD)(LOBYTE(LOWORD(winver))) >= 6) { // Don't hardlink with SHGetKnownFolderPath to allow the game to start on XP too! typedef HRESULT (WINAPI * PSHGetKnownFolderPath)(const GUID &rfid, DWORD dwFlags, HANDLE hToken, PWSTR* ppszPath); CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); PSHGetKnownFolderPath GetKnownFolderPath = (PSHGetKnownFolderPath)GetProcAddress(GetModuleHandleA("shell32.dll"), "SHGetKnownFolderPath"); const GUID FOLDERID_SavedGames = {0x4C5C32FF, 0xBB9D, 0x43b0, {0xB5, 0xB4, 0x2D, 0x72, 0xE5, 0x4E, 0xAA, 0xA4}}; LPWSTR wszPath = NULL; HRESULT hr = GetKnownFolderPath(FOLDERID_SavedGames, kfFlagCreate | kfFlagNoAlias, NULL, &wszPath); if(SUCCEEDED(hr)) { strPath = ws2s(wszPath); } CoTaskMemFree(wszPath); CoUninitialize(); } else if((DWORD)(LOBYTE(LOWORD(winver))) == 5) { // XP CHAR szPath[MAX_PATH]; HRESULT hr = SHGetFolderPathA(NULL, CSIDL_PERSONAL | CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, szPath); if(SUCCEEDED(hr)) { strPath = szPath; strPath += "\\My Games"; } } else { arx_assert_msg(false, "Unsupported windows version (below WinXP)"); } if(!strPath.empty()) { SetEnvironmentVariable("FOLDERID_SavedGames", strPath.c_str()); } }
/* * Class: org_jdesktop_jdic_init_InitUtility * Method: setEnv * Signature: (Ljava/lang/String;Ljava/lang/String;)V */ JNIEXPORT void JNICALL Java_org_jdesktop_jdic_init_InitUtility_setEnv (JNIEnv * env, jclass /*obj*/, jstring envVar, jstring envValue) { const char* pEnvVar = env->GetStringUTFChars(envVar, JNI_FALSE); const char* pEnvValue = env->GetStringUTFChars(envValue, JNI_FALSE); if (NULL != pEnvVar) { if (NULL != pEnvValue) { #ifdef WIN32 SetEnvironmentVariable(pEnvVar, pEnvValue); #else setenv(pEnvVar, pEnvValue, 1); #endif env->ReleaseStringUTFChars(envValue, pEnvValue); } env->ReleaseStringUTFChars(envVar, pEnvVar); } }
SbBool coin_setenv(const char * name, const char * value, int overwrite) { #ifdef HAVE_GETENVIRONMENTVARIABLE /* The value is changed by the application, so we no longer need to guarantee old buffers' existence to the outside world. We therefore free buffers we are bookkeeping here. This code can be disabled without any consequence though. */ struct envvar_data * envptr, * prevptr; envptr = envlist_head; prevptr = NULL; while ((envptr != NULL) && (strcmp(envptr->name, name) != 0)) { prevptr = envptr; envptr = envptr->next; } if (envptr) { /* unlink node */ if (prevptr) prevptr->next = envptr->next; else envlist_head = envptr->next; if (envlist_tail == envptr) envlist_tail = prevptr; /* free node */ free(envptr->name); free(envptr->val); free(envptr); } /* FIXME: This is from Win32s 1.3 Bug List - how should we handle it? and what's with the typo in the function name? 20030205 larsa ==================================================================== SetEnvironmentVariables() does not handle an empty string, an equal sign (=), or foreign lowercase characters in the variable name. */ if (overwrite || (GetEnvironmentVariable(name, NULL, 0) == 0)) return SetEnvironmentVariable(name, value) ? TRUE : FALSE; else return TRUE; #else /* !HAVE_GETENVIRONMENTVARIABLE */ return (setenv(name,value,overwrite) == 0); #endif /* !HAVE_GETENVIRONMENTVARIABLE */ }
/// Make sure the specified property will not be exported to children. /// This has no effect on the current setting of the property. /// WARNING: must not be called from the auditor. /// @param[in] prop the specified property /// @param[in] forever boolean - if set, newly set values no longer exported void prop_unexport(prop_e prop, int forever) { char buf[PROP_NAME_MAX]; _prop_to_ev(prop, buf, charlen(buf)); #if defined(_WIN32) SetEnvironmentVariable(buf, NULL); #else /*_WIN32*/ putil_unsetenv(buf); #endif /*_WIN32*/ if (forever) { proptab[prop].pr_flags &= ~PROP_FLAG_EXPORT; } return; }
xlw::PathUpdater::PathUpdater() { MEMORY_BASIC_INFORMATION theInfo ; HMODULE theHandle = NULL; char theDLLPathChar [MAX_PATH + 1] = ""; DWORD dwRet = 0; std::string originalPathValue(StringUtilities::getEnvironmentVariable("PATH")); bool ok(!originalPathValue.empty()); dwRet = static_cast<DWORD>(VirtualQuery (((LPCVOID)this), &theInfo,(static_cast<DWORD> (sizeof (MEMORY_BASIC_INFORMATION))))); if (dwRet) { theHandle = ((HMODULE) (theInfo.AllocationBase)); GetModuleFileName (theHandle, theDLLPathChar , MAX_PATH); xlw::XlfServices.StatusBar = theDLLPathChar; } else { ok = false; std::cerr << XLW__HERE__ <<" Could not attain path of DLL" << std::endl; } if(ok) { std::string theDLLPath(theDLLPathChar); std::string newPathValue(originalPathValue); std::string::size_type pos = theDLLPath.find_last_of("\\"); newPathValue+= ";"+theDLLPath.substr(0,pos); if (!SetEnvironmentVariable("Path", newPathValue.c_str())) { std::cerr << XLW__HERE__ << " SetEnvironmentVariable failed to set PATH" << std::endl; ok = false; } else { std::cerr << XLW__HERE__ << " PATH set successfully " << std::endl; } } if(!ok) { std::cerr << XLW__HERE__ << " Warning: Unable to initialise PATH to directory of library " << std::endl; } }
/** * lw6sys_setenv * * @keyword: the environment variable to set * @value: the value of the environment variable to set * * Sets the environment variable to a given value. If value * is NULL, variable is unset. Note that unlike lw6sys_getenv_prefixed, * this function does not transform the keyword into "LW6_..." * before setting the value, so it's your responsability to * call "lw6sys_keyword_as_env" if needed. * * Return value: 1 if success, 0 if failed */ int lw6sys_setenv (lw6sys_context_t * sys_context, const char *keyword, const char *value) { int ret = 0; #ifdef LW6_MS_WINDOWS { /* * For some reason (tired of getting into MS specifics...) it's * required to use putenv *and* SetEnvironmentVariable. Putenv * is required for instance when setting GUILE_LOAD_PATH. In doubt, * we do both, the last one being the MS dedicated function, * which should overwrite the previous in case of conflict and/or * handle special characters such as '=' in a more consistent way. */ char *putenv_str = NULL; putenv_str = lw6sys_new_sprintf ("%s=%s", keyword, value); if (putenv_str) { putenv (putenv_str); LW6SYS_FREE (sys_context, putenv_str); } } ret = SetEnvironmentVariable (keyword, value) ? 1 : 0; if (!ret) { lw6sys_log (sys_context, LW6SYS_LOG_WARNING, _x_ ("SetEnvironmentVariable failed")); } #else if (value) { ret = setenv (keyword, value, 1) ? 0 : 1; } else { ret = unsetenv (keyword); } #endif return ret; }
int acl_putenv(char *str) { #ifdef ACL_WINDOWS const char *myname = "acl_putenv"; ACL_ARGV *argv = acl_argv_split(str, "="); if (argv->argc != 2) { acl_msg_error("%s(%d): input(%s) invalid", myname, __LINE__, str); return (-1); } if (!SetEnvironmentVariable(argv->argv[0], argv->argv[1])) { acl_msg_error("%s(%d): putenv(%s, %s) error(%s)", myname, __LINE__, argv->argv[0], argv->argv[1], acl_last_serror()); return (-1); } return (0); #else return (putenv(str)); #endif }
void PrependPathToEnv(const TCHAR* path) { DWORD oldPathLen = GetEnvironmentVariable(TEXT("PATH"), NULL, 0)+1; DWORD addPathLen = _tcslen(path)+1; DWORD newPathLen = addPathLen + oldPathLen; // one NULL turns into semicolon TCHAR* newPath = (TCHAR*)_alloca(sizeof(TCHAR)*newPathLen); if (newPath) { StringCchPrintf(newPath, newPathLen, TEXT("%s;"), path); for(UINT iC= 0; iC<addPathLen; iC++) { if(newPath[iC] == TEXT('\\')) newPath[iC] = '/'; } GetEnvironmentVariable(TEXT("PATH"), newPath+addPathLen, newPathLen-addPathLen ); SetEnvironmentVariable(TEXT("PATH"), newPath); } }
void __kmp_env_unset( char const * name ) { #if KMP_OS_UNIX unsetenv( name ); #elif KMP_OS_WINDOWS BOOL rc = SetEnvironmentVariable( name, NULL ); if ( ! rc ) { DWORD error = GetLastError(); __kmp_msg( kmp_ms_fatal, KMP_MSG( CantSetEnvVar, name ), KMP_ERR( error ), __kmp_msg_null ); }; // if #else #error Unknown or unsupported OS. #endif } // func __kmp_env_unset
BOOL OpSetEnv(LPVOID* p) { LPTSTR Name = GetString(p); LPTSTR Value = GetString(p); LPTSTR ExpandedValue; ExpandPath(&ExpandedValue, Value); DEBUG("SetEnv(%s, %s)", Name, ExpandedValue); BOOL Result = FALSE; if (!SetEnvironmentVariable(Name, ExpandedValue)) { FATAL("Failed to set environment variable (error %lu).", GetLastError()); Result = FALSE; } else { Result = TRUE; } LocalFree(ExpandedValue); return Result; }
int main(int argc, char *argv[]) { void *p; HINSTANCE hRtsDll, hProgDll; LPTSTR oldPath; StgClosure *main_p; RtsConfig rts_config; hs_main_t hs_main_p; // MSDN says: An environment variable has a maximum size limit of // 32,767 characters, including the null-terminating character. oldPath = malloc(32767); if (oldPath == NULL) { die("Mallocing 32767 for oldPath failed"); } if (!GetEnvironmentVariable(TEXT("PATH"), oldPath, 32767)) { if (GetLastError() == ERROR_ENVVAR_NOT_FOUND) { oldPath[0] = '\0'; } else { die("Looking up PATH env var failed"); } } setPath(); hProgDll = loadDll(progDll); if (! SetEnvironmentVariable(TEXT("PATH"), oldPath)) { printf("SetEnvironmentVariable failed (%d)\n", GetLastError()); } free(oldPath); hRtsDll = GetNonNullModuleHandle(rtsDll); hs_main_p = GetNonNullProcAddress(hRtsDll, "hs_main"); main_p = GetNonNullProcAddress(hProgDll, "ZCMain_main_static_closure"); rts_config.rts_opts_enabled = rtsOpts; rts_config.rts_opts = NULL; return hs_main_p(argc, argv, main_p, rts_config); }
DWORD up2date_createProcess(LPCTSTR commandLine) { LPWSTR *argv; int argc; DWORD error; argv = CommandLineToArgvW(commandLine, &argc); if (argv) { switch (argc) { case 2: if (!SetEnvironmentVariable( TEXT("SIP_COMMUNICATOR_AUTOUPDATE_INSTALLDIR"), *(argv + 1))) { error = GetLastError(); break; } case 1: { STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); error = CreateProcess(NULL, *argv, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi) ? 0 : GetLastError(); } break; default: error = 0; break; } LocalFree((HLOCAL) argv); } else error = GetLastError(); return error; }
/* * Configure PATH. On Windows, sometimes PATH is not set correctly * by default. */ static void configure_win_path (void) { static bool done = false; /* GLOBAL */ if (!done) { FILE *fp; fp = fopen ("c:\\windows\\system32\\route.exe", "rb"); if (fp) { const int bufsiz = 4096; struct gc_arena gc = gc_new (); struct buffer oldpath = alloc_buf_gc (bufsiz, &gc); struct buffer newpath = alloc_buf_gc (bufsiz, &gc); const char* delim = ";"; DWORD status; fclose (fp); status = GetEnvironmentVariable ("PATH", BPTR(&oldpath), (DWORD)BCAP(&oldpath)); #if 0 status = 0; #endif if (!status) { *BPTR(&oldpath) = '\0'; delim = ""; } buf_printf (&newpath, "C:\\WINDOWS\\System32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem%s%s", delim, BSTR(&oldpath)); SetEnvironmentVariable ("PATH", BSTR(&newpath)); #if 0 status = GetEnvironmentVariable ("PATH", BPTR(&oldpath), (DWORD)BCAP(&oldpath)); if (status > 0) printf ("PATH: %s\n", BSTR(&oldpath)); #endif gc_free (&gc); done = true; } } }
int SetEnv( const char *key, const char *value) { assert(key); assert(value); #ifdef WIN32 if ( !SetEnvironmentVariable(key, value) ) { dprintf(D_ALWAYS, "SetEnv(%s, %s): SetEnvironmentVariable failed, " "errno=%d\n", key, value, GetLastError()); return FALSE; } #else char *buf; buf = new char[strlen(key) + strlen(value) + 2]; sprintf(buf, "%s=%s", key, value); if( putenv(buf) != 0 ) { dprintf(D_ALWAYS, "putenv failed: %s (errno=%d)\n", strerror(errno), errno); delete[] buf; return FALSE; } char *hashed_var=0; if ( EnvVars.lookup( HashKey( key ), hashed_var ) == 0 ) { // found old one // remove old one EnvVars.remove( HashKey( key ) ); // delete old one delete [] hashed_var; // insert new one EnvVars.insert( HashKey( key ), buf ); } else { // no old one // add new one EnvVars.insert( HashKey( key ), buf ); } #endif return TRUE; }
void FWindowsPlatformProcess::AddDllDirectory(const TCHAR* Directory) { // Normalize the input directory FString NormalizedDirectory = Directory; FPaths::NormalizeDirectoryName(NormalizedDirectory); FPaths::MakePlatformFilename(NormalizedDirectory); // Get the size of the PATH variable TArray<TCHAR> PathVariable; PathVariable.AddUninitialized(::GetEnvironmentVariable(TEXT("PATH"), NULL, 0)); // Get the actual value of variable. if (::GetEnvironmentVariable(TEXT("PATH"), PathVariable.GetData(), PathVariable.Num()) == 0) { // Log a warning if reading value fails, but continue anyway. UE_LOG(LogWindows, Warning, TEXT("Failed to load PATH environment variable. It either doesn't exist, or is too long.")); PathVariable.Add(TEXT(';')); } // Set the new path variable with the input directory at the start. Skip over any existing instances of the input directory. FString NewPathVariable = NormalizedDirectory; for(const TCHAR* PathPos = PathVariable.GetData(); PathPos < PathVariable.GetData() + PathVariable.Num(); ) { // Scan to the end of this directory const TCHAR* PathEnd = PathPos; while(*PathEnd != ';' && *PathEnd != 0) PathEnd++; // Add it to the new path variable if it doesn't match the input directory if(PathEnd - PathPos != NormalizedDirectory.Len() || FCString::Strnicmp(*NormalizedDirectory, PathPos, PathEnd - PathPos) != 0) { NewPathVariable.AppendChar(TEXT(';')); NewPathVariable.AppendChars(PathPos, PathEnd - PathPos); } // Move to the next string PathPos = PathEnd + 1; } SetEnvironmentVariable(TEXT("PATH"), *NewPathVariable); }
void SteamLoader::Initialize() { if (IsSteamRunning(true)) { std::wstring steamDllPath = GetSteamDllPath(); std::wstring steamDirectory = steamDllPath.substr(0, steamDllPath.rfind(L'\\')); // add Steam to the process path static wchar_t pathBuffer[65536]; GetEnvironmentVariable(L"PATH", pathBuffer, sizeof(pathBuffer)); wcscat(pathBuffer, L";"); wcscat(pathBuffer, steamDirectory.c_str()); SetEnvironmentVariable(L"PATH", pathBuffer); // load steamclient*.dll m_hSteamClient = LoadLibrary(steamDllPath.c_str()); //LoadGameOverlayRenderer(steamDllPath); } }
int WINAPI WinMain(HINSTANCE instance, HINSTANCE prevInstance, LPSTR cmdLine, int show) { TCHAR buf[2048]; int i, filename_index = 0; STARTUPINFO startup_info; PROCESS_INFORMATION process_info; SetEnvironmentVariable(_TEXT("TERATERM_EXTENSIONS"), _TEXT("1")); GetModuleFileName(NULL, buf, sizeof(buf)); for (i = 0; buf[i] != 0; i++) { if (buf[i] == _TEXT('\\') || buf[i] == _TEXT('/') || buf[i] == _TEXT(':')) { filename_index = i + 1; } } _tcsncpy(buf + filename_index, _TEXT("ttermpro.exe"), sizeof(buf) - filename_index); GetStartupInfo(&startup_info); CreateProcess(buf, GetCommandLine(), NULL, NULL, FALSE, 0, NULL, NULL, &startup_info, &process_info); return 0; }
BOOL AddEasyHookEnv() { TCHAR dir[MAX_PATH]; int dirlen = GetModuleFileName(GetDLLInstance(), dir, MAX_PATH); LPTSTR lpfilename=dir+dirlen; while (lpfilename>dir && *lpfilename!=_T('\\') && *lpfilename!=_T('/')) --lpfilename; *lpfilename = 0; _tcscat(dir, _T(";")); dirlen = _tcslen(dir); int sz=GetEnvironmentVariable(_T("path"), NULL, 0); LPTSTR lpPath = (LPTSTR)malloc((sz+dirlen+2)*sizeof(TCHAR)); GetEnvironmentVariable(_T("path"), lpPath, sz); if (!_tcsstr(lpPath, dir)) { if (lpPath[sz-2]!=_T(';')) _tcscat(lpPath, _T(";")); _tcscat(lpPath, dir); SetEnvironmentVariable(_T("path"), lpPath); } free(lpPath); return true; }
void set_ansicon( PCONSOLE_SCREEN_BUFFER_INFO pcsbi ) { CONSOLE_SCREEN_BUFFER_INFO csbi; TCHAR buf[64]; if (pcsbi == NULL) { HANDLE hConOut; hConOut = CreateFile( L"CONOUT$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0 ); GetConsoleScreenBufferInfo( hConOut, &csbi ); CloseHandle( hConOut ); pcsbi = &csbi; } wsprintf( buf, L"%dx%d (%dx%d)", pcsbi->dwSize.X, pcsbi->dwSize.Y, pcsbi->srWindow.Right - pcsbi->srWindow.Left + 1, pcsbi->srWindow.Bottom - pcsbi->srWindow.Top + 1 ); SetEnvironmentVariable( L"ANSICON", buf ); }
/* Change or add an environment variable. * name (in) - name of the varilable to add or change * value (in) - value of variable to set * buffer (out) - if not NULL then *nix putenv() semantics is * used, so that address of the variable's value * is saved in this argument. * It's your task to clean up this memory with * free() call. On Windows NULL is returned. * Returns: * 0 - in case of success, * 1 - in case of error. */ int uSetEnvironmentVariable(const char* name, const char* value, char** buffer, sys_call_error_fun fun) { #ifdef _WIN32 BOOL res; if(buffer) *buffer = NULL; res = SetEnvironmentVariable( name, /* environment variable name */ value); /* new value for variable */ if (res == 0) { sys_call_error("SetEnvironmentVariable"); return 1; } return 0; #else int name_len = strlen(name); int value_len = strlen(value); /* This string will become the part * of the environment, so we must not delete it there. */ char *str = (char*)malloc(name_len + value_len + 2); if(buffer) *buffer = str; memcpy(str, name, name_len); str[name_len] = '='; memcpy(str + name_len + 1, value, value_len); str[name_len + value_len + 1] = '\0'; int res = putenv(str); if (res != 0) { sys_call_error("putenv"); return 1; } return 0; #endif }
// static void Environment::SetEnvironmentVariable(StringIn name, StringIn value, EnvironmentVariableTarget target) { if (target == EnvironmentVariableTarget_Process) { SetEnvironmentVariable(name, value); } else { if (target == EnvironmentVariableTarget_User) { // HKEY_CURRENT_USER\Environment MS::Win32::RegistryKey regKey = MS::Win32::Registry::OpenKey(HKEY_CURRENT_USER, L"Environment"); regKey.SetStringValue(name, value); } else { // HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment registry key, } // then broadcast a WM_SETTINGCHANGE message with lParam set to the string "Environment". PostMessageW(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM)L"Environment"); } }
R_API int r_sys_setenv(const char *key, const char *value) { #if __UNIX__ || __CYGWIN__ && !defined(MINGW32) if (!key) { return 0; } if (!value) { unsetenv (key); return 0; } return setenv (key, value, 1); #elif __WINDOWS__ LPTSTR key_ = r_sys_conv_utf8_to_utf16 (key); LPTSTR value_ = r_sys_conv_utf8_to_utf16 (value); SetEnvironmentVariable (key_, value_); free (key_); free (value_); return 0; // TODO. get ret #else #warning r_sys_setenv : unimplemented for this platform return 0; #endif }
int _tmain(int argc, _TCHAR* argv[]) { _tsetlocale(LC_ALL, _T("Russian")); _tprintf(_T("Сколько файлов желаете создать???:\n")); size_t c = -1; int count = 0; _tscanf_s(_T("%d"), &c); STARTUPINFO si; PROCESS_INFORMATION pi; memset(&si, 0, sizeof(STARTUPINFO)); si.cb = sizeof(STARTUPINFO); SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS); SYSTEMTIME st; FILETIME ft; GetLocalTime(&st); SystemTimeToFileTime(&st, &ft); __int64 minTime = (__int64(ft.dwHighDateTime) << 32) | __int64(ft.dwLowDateTime); char value[MAX_PATH]; //*((__int64*)value) = minTime; _i64toa(minTime, value, 10); wchar_t* wString = new wchar_t[4096]; MultiByteToWideChar(CP_ACP, 0, value, -1, wString, 4096); SetEnvironmentVariable(_T("NotepadTime"), wString); while (count < c) { TCHAR ProcName[] = _T("1_Notepad.exe"); BOOL flag = CreateUnsuspendedProcess(ProcName, &si, &pi); WaitForSingleObject(pi.hProcess, INFINITE); count++; } TCHAR ProcName1[] = _T("2_FindAndGetInfo.exe"); BOOL b = CreateUnsuspendedProcess(ProcName1, &si, &pi); WaitForSingleObject(pi.hProcess, INFINITE); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); return 0; }
void __kmp_env_set(char const *name, char const *value, int overwrite) { #if KMP_OS_UNIX int rc = setenv(name, value, overwrite); if (rc != 0) { // Dead code. I tried to put too many variables into Linux* OS // environment on IA-32 architecture. When application consumes // more than ~2.5 GB of memory, entire system feels bad. Sometimes // application is killed (by OS?), sometimes system stops // responding... But this error message never appears. --ln __kmp_fatal(KMP_MSG(CantSetEnvVar, name), KMP_HNT(NotEnoughMemory), __kmp_msg_null); } #elif KMP_OS_WINDOWS BOOL rc; if (!overwrite) { rc = GetEnvironmentVariable(name, NULL, 0); if (rc) { // Variable exists, do not overwrite. return; } DWORD error = GetLastError(); if (error != ERROR_ENVVAR_NOT_FOUND) { __kmp_fatal(KMP_MSG(CantGetEnvVar, name), KMP_ERR(error), __kmp_msg_null); } } rc = SetEnvironmentVariable(name, value); if (!rc) { DWORD error = GetLastError(); __kmp_fatal(KMP_MSG(CantSetEnvVar, name), KMP_ERR(error), __kmp_msg_null); } #else #error Unknown or unsupported OS. #endif } // func __kmp_env_set
void ngx_set_inherited_listen_sockets(ngx_cycle_t *cycle) { char *var; u_char *p; ngx_listening_t *ls; ngx_uint_t i; var = ngx_alloc(cycle->listening.nelts * (NGX_INT32_LEN + 1) + 1, cycle->log); // (numberMaxLen + ';') * n + '\0' p = var; ls = cycle->listening.elts; for (i = 0; i < cycle->listening.nelts; i++) { p = ngx_sprintf(p, "%d;", (int)ls[i].fd); } *p = '\0'; SetEnvironmentVariable(NGINX_VAR, var); ngx_free(var); }
int unsetenv(const char *name) { SetEnvironmentVariable(name, NULL); return 0; }
int setenv(const char *name, const char *value, int overwrite) { return (int)SetEnvironmentVariable(name, value); }
int main(int argc, char *argv[]) { #ifdef WINDOWS HANDLE hchild; int child; #else pid_t child; #endif int rc; int arg_offs = 1; const char *outfile = NULL; const char *pidfile = NULL; if (argc < 2) { return usage(argv[0]); } while (argv[arg_offs][0] == '-') { if (strcmp(argv[arg_offs], "-env") == 0) { if (argc <= arg_offs + 2) return usage(argv[0]); #if VERBOSE fprintf(stderr, "setting env var \"%s\" to \"%s\"\n", argv[arg_offs + 1], argv[arg_offs + 2]); #endif #ifdef WINDOWS rc = SetEnvironmentVariable(argv[arg_offs + 1], argv[arg_offs + 2]); #else rc = setenv(argv[arg_offs + 1], argv[arg_offs + 2], 1 /*overwrite*/); #endif if (rc != 0 || strcmp(mygetenv(argv[arg_offs + 1]), argv[arg_offs + 2]) != 0) { fprintf(stderr, "error in setenv of \"%s\" to \"%s\"\n", argv[arg_offs + 1], argv[arg_offs + 2]); fprintf(stderr, "setenv returned %d\n", rc); fprintf(stderr, "env var \"%s\" is now \"%s\"\n", argv[arg_offs + 1], mygetenv(argv[arg_offs + 1])); exit(1); } arg_offs += 3; } else if (strcmp(argv[arg_offs], "-out") == 0) { if (argc <= arg_offs + 1) return usage(argv[0]); outfile = argv[arg_offs + 1]; arg_offs += 2; } else if (strcmp(argv[arg_offs], "-pid") == 0) { if (argc <= arg_offs + 1) return usage(argv[0]); pidfile = argv[arg_offs + 1]; arg_offs += 2; } else { return usage(argv[0]); } if (argc - arg_offs < 1) return usage(argv[0]); } #ifdef UNIX child = fork(); if (child < 0) { perror("ERROR on fork"); } else if (child == 0) { /* redirect std{out,err} */ redirect_stdouterr(outfile); execv(argv[arg_offs], argv + arg_offs /*include app*/); fprintf(stderr, "execv of %s FAILED", argv[arg_offs]); exit(1); } /* else, parent, and we continue below */ if (pidfile == NULL) printf("%d\n", child); #else /* redirect std{out,err} */ redirect_stdouterr(outfile); /* Do we want _P_DETACH instead of _P_NOWAIT? _P_DETACH doesn't return the * child handle though. */ hchild = (HANDLE)_spawnv(_P_NOWAIT, argv[arg_offs], argv + arg_offs /*include app*/); if (hchild == INVALID_HANDLE_VALUE) { fprintf(stderr, "_spawnv of %s FAILED", argv[arg_offs]); exit(1); } child = process_id_from_handle(hchild); #endif if (pidfile != NULL) { FILE *f = fopen(pidfile, "w"); if (f == NULL) { perror("open pidfile failed"); exit(1); } fprintf(f, "%d\n", child); fclose(f); } return 0; }