I am trying to call function CreateProcessAsUser. Passing constant string is fine. Trying to pick up an Environment variable using char* getenv(const char name) is causing me a problem.
If I use the following, notepad.exe will run.
CreateProcessAsUser(hTokenDup, _T("c:\\windows\\notepad.exe"),
_T("c:\\windows\\notepad.exe"), NULL, NULL, FALSE,
dwCreationFlag, pEnvironment, NULL, &si, &pi);
However, if I use the following nothing runs.
CreateProcessAsUser(hTokenDup, _T("MyAppName"),
(LPTSTR)getenv("MYENVVAR"), NULL, NULL, FALSE,
dwCreationFlag, pEnvironment, NULL, &si, &pi);
Have I specified the getenv and (LPTSTR) correctly?
I have tried using user and system environment vars containing c:\\windows\\notepad.exe and c:\windows\notepad.exe.
Thanks!
The third parameter, lpCommandLine
is LPTSTR
which means it must be writeable memory. You need to copy the command line into a writeable string before calling CreateProcessAsUser
.
The documentation for getenv
states:
It is not safe to modify the value of the environment variable using the returned pointer.
You therefore cannot pass this as the lpCommandLine
parameter of CreateProcessAsUser
.
Your first call to CreateProcessAsUser
appears to be wrong too since you also are not passing writeable memory for lpCommandLine
.
Of course it's most likely that your immediate problem is that you are mixing ANSI and Unicode. If your app is Unicode then you need to call _wgetenv
, or _tgetenv
if you really do want to target both ANSI and Unicode from the same source. But make sure you copy it into a writeable buffer before passing it on.
Finally, as Adam commented, every time you write a cast, there is a strong possibility that you are making a mistake.