【问题标题】:CreateProcessAsUser returned with error code 2CreateProcessAsUser 返回错误代码 2
【发布时间】:2012-07-03 09:56:09
【问题描述】:

我的应用中有两个进程。 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);
}

【问题讨论】:

    标签: c++ windows visual-studio winapi


    【解决方案1】:

    默认情况下,Windows 服务在System32 目录中执行。这就是为什么在没有指定绝对路径时找不到其他可执行文件的原因。您可以通过从 Windows 服务获取GetCurrentDirectory() 来确认这一点。

    要解决这个问题(假设 Windows 服务和其他可执行文件位于同一目录中):

    • 使用GetModuleFileName() 获取Windows 服务可执行文件的完整路径,将NULL 作为第一个参数传递。
    • 从完整路径中提取目录
    • 然后构建其他可执行文件的路径并将其传递给CreateProcessAsUser() 或使用SetCurrentDirectory() 更改Windows 服务的目录

    【讨论】:

    • 这不是我面临的问题。 GetCommandLineA() 返回“myService.exe”的路径,而不是 System32 目录。我通过逐步验证了它。
    • 我试过了。 GetCurrentDirectory() 返回 System32 目录路径。 GetCommandLine() 给出代码生成的exe路径。
    • 是的,所以windows服务是在System32中运行的,这就是GetCurrentDirectory()告诉你的。
    猜你喜欢
    • 1970-01-01
    • 2019-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-11
    • 2017-02-06
    • 2011-12-04
    • 2014-07-03
    相关资源
    最近更新 更多