CreateProcessAsUser多个应用程序实例?

时间:2014-01-17 17:18:14

标签: c# windows-services createprocessasuser

我正在尝试使用CreateProcessAsUser启动服务,但出于某种原因,在调试时会创建多个(30+)EXE实例。这些进程开始在这行代码中产生:

ret = CreateProcessAsUser(DupedToken, Path, null, ref sa, ref sa, false, 0, (IntPtr)0, "c:\\", ref si, out pi);

我使用了此示例中的代码 - http://support.microsoft.com/default.aspx?scid=kb;EN-US;889251

    [StructLayout(LayoutKind.Sequential)]
    public struct STARTUPINFO
    {
        public int cb;
        public String lpReserved;
        public String lpDesktop;
        public String lpTitle;
        public uint dwX;
        public uint dwY;
        public uint dwXSize;
        public uint dwYSize;
        public uint dwXCountChars;
        public uint dwYCountChars;
        public uint dwFillAttribute;
        public uint dwFlags;
        public short wShowWindow;
        public short cbReserved2;
        public IntPtr lpReserved2;
        public IntPtr hStdInput;
        public IntPtr hStdOutput;
        public IntPtr hStdError;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct PROCESS_INFORMATION
    {
        public IntPtr hProcess;
        public IntPtr hThread;
        public uint dwProcessId;
        public uint dwThreadId;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct SECURITY_ATTRIBUTES
    {
        public int Length;
        public IntPtr lpSecurityDescriptor;
        public bool bInheritHandle;
    }

    [DllImport("kernel32.dll", EntryPoint = "CloseHandle", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
    public extern static bool CloseHandle(IntPtr handle);

    [DllImport("advapi32.dll", EntryPoint = "CreateProcessAsUser", SetLastError = true, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
    public extern static bool CreateProcessAsUser(IntPtr hToken, String lpApplicationName, String lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes,
        ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandle, int dwCreationFlags, IntPtr lpEnvironment,
        String lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);

    [DllImport("advapi32.dll", EntryPoint = "DuplicateTokenEx")]
    public extern static bool DuplicateTokenEx(IntPtr ExistingTokenHandle, uint dwDesiredAccess,
        ref SECURITY_ATTRIBUTES lpThreadAttributes, int TokenType,
        int ImpersonationLevel, ref IntPtr DuplicateTokenHandle);





      string curFile2 = AppDomain.CurrentDomain.BaseDirectory + "OnStart.txt";

   public void createProcessAsUser()
   {
       IntPtr Token = new IntPtr(0);
        IntPtr DupedToken = new IntPtr(0);
        bool      ret;
        //Label2.Text+=WindowsIdentity.GetCurrent().Name.ToString();


        SECURITY_ATTRIBUTES sa  = new SECURITY_ATTRIBUTES();
        sa.bInheritHandle       = false;
        sa.Length               = Marshal.SizeOf(sa);
        sa.lpSecurityDescriptor = (IntPtr)0;

        Token = WindowsIdentity.GetCurrent().Token;

        const uint GENERIC_ALL = 0x10000000;

        const int SecurityImpersonation = 2;
        const int TokenType = 1;

        ret = DuplicateTokenEx(Token, GENERIC_ALL, ref sa, SecurityImpersonation, TokenType, ref DupedToken);

        if (ret == false)
             File.AppendAllText(curFile2, "DuplicateTokenEx failed with " + Marshal.GetLastWin32Error());

        else
             File.AppendAllText(curFile2,  "DuplicateTokenEx SUCCESS");

        STARTUPINFO si          = new STARTUPINFO();
        si.cb                   = Marshal.SizeOf(si);
        si.lpDesktop            = "";

        string Path;
        Path = @"C:\myEXEpath";

        PROCESS_INFORMATION pi  = new PROCESS_INFORMATION();
        ret = CreateProcessAsUser(DupedToken, Path, null, ref sa, ref sa, false, 0, (IntPtr)0, "c:\\", ref si, out pi);

        if (ret == false)
             File.AppendAllText(curFile2, "CreateProcessAsUser failed with " + Marshal.GetLastWin32Error());
        else
        {
             File.AppendAllText(curFile2, "CreateProcessAsUser SUCCESS.  The child PID is" + pi.dwProcessId);

            CloseHandle(pi.hProcess);
            CloseHandle(pi.hThread);
        }

        ret = CloseHandle(DupedToken);
        if (ret == false)
             File.AppendAllText(curFile2, Marshal.GetLastWin32Error().ToString() );
        else
             File.AppendAllText(curFile2, "CloseHandle SUCCESS");
    }

enter image description here

1 个答案:

答案 0 :(得分:1)

上面列出的步骤将为每次执行方法createProcessAsUser()生成一个进程。现在,此方法不包含任何终止或终止进程的代码,因此重复调用此方法将生成多个进程。当您的代码显示时,该方法将只生成一个进程。

我认为真正的答案是你如何称呼这种方法。正如你在评论中所述

  

我正在尝试在用户会话中启动.exe

我只能假设您可能正在从Session开始,Application_BeginRequest或其他可能多次执行的方法调用此过程,具体取决于您的应用程序的设计方式(此方法的调用代码将很好编辑)。

正如我之前所说,每次调用方法时都会执行exe而不会终止。如果您只想要运行一个应用程序实例,则必须检查进程树以确定该进程是否已在运行。现在,如果您应该为每个用户运行一个进程,则需要执行上述操作,但还要保留引用第一次应用程序启动时创建的进程ID。

查看以下代码以了解更改(简化)

public void createProcessAsUser()
{
    //one process per session
    object sessionPID = Session["_servicePID"];
    if (sessionPID != null && sessionPID is int && Process.GetProcessById((int)sessionPID) != null)
        return; //<-- Return process already running for session
    else
        Session.Remove("_servicePID");

    //one process per application
    object applicationPID = Application["_applicationPID"];
    if (applicationPID != null && applicationPID is int && Process.GetProcessById((int)applicationPID) != null)
        return; //<-- Process running for application
    else
        Application.Remove("_applicationPID");

    //omitted starting code

    if (ret == false)
        // omitted log failed
    else
    {
        // omitted log started

        //for one process per session
        Session["_servicePID"] = Convert.ToInt32(pi.dwProcessId);

        //for one process per application
        Application["_applicationPID"] = Convert.ToInt32(pi.dwProcessId);

        //close handles
    }

    // omitted the rest of the method
}

这个简单方法将对应用程序创建的进程ID的引用保存到每个用户一个进程的Session状态或每个应用程序实例一个进程的Application状态。

现在,如果这是预期的结果,您可能还希望在应用程序关闭(正常)或会话结束时查看终止进程。这与我们的第一次检查非常相似,但可以如下所示完成。 *请注意,这不会考虑工作进程关闭而不调用会话\应用程序结束事件,这些事件也应该在应用程序启动时处理。

//session end
void Session_End(object sender, EventArgs e)
{
    object sessionPID = Session["_servicePID"];
    if (sessionPID != null && sessionPID is int)
    {
        Process runningProcess = Process.GetProcessById((int)sessionPID);
        if (runningProcess != null)
            runningProcess.Kill();
    }
}

//application end
void Application_End(object sender, EventArgs e)
{
    object applicationPID = Application["_applicationPID"];
    if (applicationPID != null && applicationPID is int && Process.GetProcessById((int)applicationPID) != null)
    {
        Process runningProcess = Process.GetProcessById((int)applicationPID);
        if (runningProcess != null)
            runningProcess.Kill();
    }
}

再次回到原始问题,如何停止多个实例。答案就是通过检查如何启动实例(即方法createProcessAsUser()的调用代码)来停止生成多个实例的能力,并相应地调整方法以避免多次调用。

如果此实用程序有助于发布有关如何调用createProcessAsUser()方法的详细信息,请发布编辑。

更新1:

Session \ Application在上下文中不存在。如果方法createProcessUser()与ASPX页面不同,则会发生这种情况(就像在教程中一样)。

因此,您需要更改HttpContext的存在,这可以通过调用

来完成

HttpContext.Currrent

我已采用上述方法将检查包括在HttpContext

public void createProcessAsUser()
{
    //find the http context
    var ctx = HttpContext.Current;
    if (ctx == null)
        throw new Exception("No Http Context");

    //use the following code for 1 process per user session
    object sessionPID = ctx.Session["_servicePID"];
    if (sessionPID != null && sessionPID is int && Process.GetProcessById((int)sessionPID) != null)
        return; //<-- Return process already running for session
    else
        ctx.Session.Remove("_servicePID");

    //use the following code for 1 process per application instance
    object applicationPID = ctx.Application["_applicationPID"];
    if (applicationPID != null && applicationPID is int && Process.GetProcessById((int)sessionPID) != null)
        return; //<-- Process running for application
    else
        ctx.Application.Remove("_applicationPID");

    // omitted code

    if (ret == false)
    {
        //omitted logging
    }
    else
    {
        //omitted logging

        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);


        //for one process per session
        ctx.Session["_servicePID"] = Convert.ToInt32(pi.dwProcessId);

        //for one process per application
        ctx.Application["_applicationPID"] = Convert.ToInt32(pi.dwProcessId);
    }

    //omitted the rest
}

您不会通过调用HttpContext

来获取当前using System.Web(您必须添加var ctx = HttpContext.Current)的前几行中的更改

接下来我们只检查ctx变量是否为空。如果它为null我会抛出异常,但无论如何你都可以处理它。

从那里直接调用SessionApplication而不是直接调用ctx.Session...ctx.Application...

更新2:

这是一个调用上述方法的Windows应用程序。现在这改变了球类游戏,因为上面的代码实际上意味着开始一个过程作为模拟的Windows身份。现在,模拟通常是在WebApplications而不是WinForms中完成的(尽管可以这样做)。

如果您没有模仿与运行该应用程序的用户不同的用户。意味着登录的用户是运行该应用程序的用户。如果是这样,那么您的代码将变得 ALOT 更容易。

以下是如何实现这一目标的示例。

/// <summary>
/// static process ID value
/// </summary>
static int? processID = null;

public void startProcess()
{
    //check if the processID has a value and if the process ID is active
    if (processID.HasValue && Process.GetProcessById(processID.Value) != null)
        return;

    //start a new process
    var process = new Process();
    var processStartInfo = new ProcessStartInfo(@"C:\myProg.exe");
    processStartInfo.CreateNoWindow = true;
    processStartInfo.UseShellExecute = false;
    process.StartInfo = processStartInfo;
    process.Start();
    //set the process id
    processID = process.Id;
}

再次,因为这是一个Win Forms应用程序,您可以使用Process对象来启动进程,此Windows应用程序将作为运行Windows窗体应用程序的用户运行。在此示例中,我们还持有对processID的静态引用,并检查processID(如果找到)是否已在运行。