我的应用程序中有两个进程。1.“myService.exe”是一个windows服务。2.“myApp.exe”与“myService.exe”位于同一目录下。
此进程由“myService.exe”使用 CreateProcessAsUser api 生成。我们必须使用这个 api 而不是直接启动进程(使用系统调用),因为我们需要访问当前用户的 vpn 配置文件。
当我对“myApp.exe”的路径进行硬编码时,它工作正常并创建了进程,但是通过获取“myService.exe”的当前目录获得的相同路径没有创建进程并返回错误代码2(找不到文件) .
我正在使用 Visual Studio 2008。该项目以 ASCII 模式编译,而不是下面代码中的 Unicode。我尝试使用Unicode api(最后没有'A')。它也没有用。
问题不在于获取当前路径。已验证该路径不是 System32 文件夹。
HANDLE hToken;
LPSTR exePath = GetCommandLineA();
string exePathStr = exePath;
char fileExeChar[256];
strcpy(fileExeChar,exePathStr.c_str());
string serverExe = "myService.exe";
for(unsigned int i=0;i<exePathStr.length()-(serverExe.length() + 1);i++)
{
fileLocation += fileExeChar[i];// removing the service.exe from the path
}
LPSTR fileLocationLp = const_cast<LPSTR>(fileLocation.c_str());
LPCSTR progName = (LPCSTR)"myapp.exe";
char errStr[100];
DWORD dwCreationFlag = NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE;
STARTUPINFO si;
PROCESS_INFORMATION pi;
int k = WTSQueryUserToken (WTSGetActiveConsoleSessionId (), &hToken);
ZeroMemory( &si, sizeof( STARTUPINFO ) );
si.cb = sizeof( STARTUPINFO );
si.lpDesktop = (LPSTR)"winsta0\\default";
ZeroMemory( &pi,sizeof(pi));
if ( !CreateProcessAsUserA(
hToken,
progName,
fileLocationLp,
NULL,
NULL,
FALSE,
dwCreationFlag,
NULL,
NULL,
&si,
&pi
) )
{
sprintf(errStr, "CreateProcessAsUser Failed %d\n", GetLastError());
}
else
{
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
CloseHandle(hToken);
}