Ajaykrishnan R
Ajaykrishnan R

Reputation: 207

How to keep cmd.exe started with PseudoConsole alive even after parent exits?

So i have server.cs which spawns the child daemon.exe as follows:

bool success = CreateProcess(
    null,
    "daemon.exe",   
    IntPtr.Zero,
    IntPtr.Zero,
    false,
    DETACHED_PROCESS, 
    IntPtr.Zero,
    null,
    ref si,
    out pi
);

inside the daemon i spawn a cmd.exe as follows:

string app = @"C:\Windows\System32\cmd.exe";
bool success = CreateProcess(
    null,
    app,
    IntPtr.Zero,    
    IntPtr.Zero,
    false,
    EXTENDED_STARTUPINFO_PRESENT,
    IntPtr.Zero,
    null,
    ref si,
    out pi
);

When i kill server.exe, cmd.exe is killed too which i want to persist indefinitely. If i break daemon.exe using something like Console.ReadLine() it does survive the server exiting as intended with DETACHED_PROCESS however for some reason cmd.exe dies despite being spawned by the daemon. I am guessing its because cmd.exe is still attaching to server's console but I dont know for sure and dont understand why

It works if I spawn cmd.exe using CREATE_NEW_CONSOLE flag but doing so I lose PseudoConsole functionality alltogether as output gets piped to the new console.

EDIT:

STARTUPINFOEX preparation for daemon.cs :

IntPtr lpSize = IntPtr.Zero;
InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref lpSize);

STARTUPINFOEX si = new();
si.lpAttributeList = Marshal.AllocHGlobal(lpSize);


InitializeProcThreadAttributeList(si.lpAttributeList, 1, 0, ref lpSize);
si.StartupInfo.cb = Marshal.SizeOf<STARTUPINFOEX>();

UpdateProcThreadAttribute(
    si.lpAttributeList,
    0,
    (IntPtr)PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE,
    phPC,
    (IntPtr)Marshal.SizeOf(phPC),
    IntPtr.Zero,
    IntPtr.Zero
);


PROCESS_INFORMATION pi = new();

STARTUPINFOEX preparation for server.cs :

STARTUPINFOEX si = new();
PROCESS_INFORMATION pi = new();

Upvotes: 0

Views: 59

Answers (0)

Related Questions