Cómo llamar a CreateProcess () con STARTUPINFOEX desde C # y volver a criar al hijo

Necesito crear un nuevo proceso, pero para que sea un "hijo" de otro proceso, no del proceso actual, por ejemplo, re-padre del nuevo proceso.

Los siguientes me tienen casi allí.NET: Cómo llamar a CreateProcessAsUser () con STARTUPINFOEX desde C # y.NET: cómo hacer que UpdateProcThreadAttribute yhttp://winprogger.com/launching-a-non-child-process/

<code>using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;

public class ProcessCreator
{
    [DllImport("kernel32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool CreateProcess(
        string lpApplicationName, string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes,
        ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandles, uint dwCreationFlags,
        IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFOEX lpStartupInfo,
        out PROCESS_INFORMATION lpProcessInformation);

    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool UpdateProcThreadAttribute(
        out IntPtr lpAttributeList, uint dwFlags, IntPtr Attribute, IntPtr lpValue,
        IntPtr cbSize, IntPtr lpPreviousValue, IntPtr lpReturnSize);

    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool InitializeProcThreadAttributeList(
        out IntPtr lpAttributeList, int dwAttributeCount, int dwFlags, ref IntPtr lpSize);

    public static bool CreateProcess(int parentProcessId)
    {
        const uint EXTENDED_STARTUPINFO_PRESENT = 0x00080000;
        const int PROC_THREAD_ATTRIBUTE_PARENT_PROCESS = 0x00020000;

        var pInfo = new PROCESS_INFORMATION();
        var sInfoEx = new STARTUPINFOEX();
        sInfoEx.StartupInfo = new STARTUPINFO();

        if (parentProcessId > 0)
        {
            var lpSize = IntPtr.Zero;
            IntPtr dummyPtr;
            var success = InitializeProcThreadAttributeList(out dummyPtr, 1, 0, ref lpSize);
            if (success || lpSize == IntPtr.Zero)
            {
                return false;
            }

            sInfoEx.lpAttributeList = Marshal.AllocHGlobal(lpSize);
            if (sInfoEx.lpAttributeList == IntPtr.Zero)
            {
                return false;
            }

            success = InitializeProcThreadAttributeList(out sInfoEx.lpAttributeList, 1, 0, ref lpSize);
            if (!success)
            {
                return false;
            }

            var parentHandle = Process.GetProcessById(parentProcessId).Handle;
            success = UpdateProcThreadAttribute(
                out sInfoEx.lpAttributeList,
                0,
                (IntPtr)PROC_THREAD_ATTRIBUTE_PARENT_PROCESS,
                parentHandle,
                (IntPtr)IntPtr.Size,
                IntPtr.Zero,
                IntPtr.Zero);
            if (!success)
            {
                return false;
            }

            sInfoEx.StartupInfo.cb = Marshal.SizeOf(sInfoEx);
        }


        var pSec = new SECURITY_ATTRIBUTES();
        var tSec = new SECURITY_ATTRIBUTES();
        pSec.nLength = Marshal.SizeOf(pSec);
        tSec.nLength = Marshal.SizeOf(tSec);
        var lpApplicationName = Path.Combine(Environment.SystemDirectory, "notepad.exe");
        return CreateProcess(lpApplicationName, null, ref pSec, ref tSec, false, EXTENDED_STARTUPINFO_PRESENT, IntPtr.Zero, null, ref sInfoEx, out pInfo);
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    struct STARTUPINFOEX
    {
        public STARTUPINFO StartupInfo;
        public IntPtr lpAttributeList;
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    struct STARTUPINFO
    {
        public Int32 cb;
        public string lpReserved;
        public string lpDesktop;
        public string lpTitle;
        public Int32 dwX;
        public Int32 dwY;
        public Int32 dwXSize;
        public Int32 dwYSize;
        public Int32 dwXCountChars;
        public Int32 dwYCountChars;
        public Int32 dwFillAttribute;
        public Int32 dwFlags;
        public Int16 wShowWindow;
        public Int16 cbReserved2;
        public IntPtr lpReserved2;
        public IntPtr hStdInput;
        public IntPtr hStdOutput;
        public IntPtr hStdError;
    }

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

    [StructLayout(LayoutKind.Sequential)]
    public struct SECURITY_ATTRIBUTES
    {
        public int nLength;
        public IntPtr lpSecurityDescriptor;
        public int bInheritHandle;
    }
}
</code>

ProcessCreator.CreateProcess (0) inicia el Bloc de notas como un elemento secundario del proceso actual, que es el comportamiento predeterminado. Hasta ahora tan bueno.

Si el valor pasado no es 0, el código intenta iniciar el Bloc de notas como un elemento secundario del proceso cuyo ID de proceso coincide con el valor de entrada (supongo que el proceso existe por ahora).

Lamentablemente esa parte no funciona y lanza la siguiente excepción:

Se detectó FatalExecutionEngineError Mensaje: El tiempo de ejecución ha encontrado un error fatal. La dirección del error estaba en 0x69a2c7ad, en el hilo 0x1de0. El código de error es 0xc0000005. Este error puede ser un error en el CLR o en las partes inseguras o no verificables del código de usuario. Las fuentes comunes de este error incluyen errores de cálculo de cuentas del usuario para interoperabilidad COM o PInvoke, que pueden dañar la pila.

Cualquier punteros muy apreciados.

Respuestas a la pregunta(1)

Su respuesta a la pregunta