Start new process, without being a child of the sp

2019-01-17 21:09发布

问题:

How would I go about starting a new process without it being the child of the calling process.

Example:

Main Program (Caller.exe)

process.start("file.exe")

Image:

回答1:

If the spawning process (parent) ends before the spawned process (child) does, then the parent-child chain is broken. To make use of this, you'd have to use an intermediate stub-process like so:

Caller.exe → Stub.exe → File.exe.

Here Stub.exe is simple launcher program that ends just after starting File.exe.



回答2:

If you start a process, then you'll be its parent.

Maybe you could try to start your process from cmd.exe instead, so cmd.exe will be the parent.

Process proc = Process.Start(new ProcessStartInfo { Arguments = "/C explorer", FileName = "cmd", WindowStyle = ProcessWindowStyle.Hidden });


回答3:

This runs new process without parent:

System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo();
psi.FileName = @"cmd";
psi.Arguments = "/C start notepad.exe";
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
System.Diagnostics.Process.Start(psi);


回答4:

The documentation of Process.Start(string fileName) says

a new process that’s started alongside already running instances 
of the same process will be independent

and it says

Starting a process by specifying its file name is similar to 
typing the information in the Run dialog box of the Windows Start menu

which to me seems consistent with independent processes.

So according to the documentation, Process.Start should do what you desire.



回答5:

Here is the code that I'm now using. I thought that it may be useful to someone. It accepts one argument. The argument is a base64 encoded string that decodes to the path of the file that you would like to run.

 Module Module1

    Sub Main()
        Dim CommandLineArgs As System.Collections.ObjectModel.ReadOnlyCollection(Of String) = My.Application.CommandLineArgs
        If CommandLineArgs.Count = 1 Then
            Try
                Dim path As String = FromBase64(CommandLineArgs(0))
                Diagnostics.Process.Start(path)
            Catch
            End Try
            End
        End If
    End Sub

    Function FromBase64(ByVal base64 As String) As String
        Dim b As Byte() = Convert.FromBase64String(base64)
        Return System.Text.Encoding.UTF8.GetString(b)
    End Function

End Module