Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# equivalent to fork()/exec()

I'm developing a program that needs to call an outside program, but needs to wait for it to execute. This is being done in C# (to which I am brand new, but have lots of experience in C++, Qt, and C) and CreateProcess does not seem to be what I'm looking for (starts the process, then forgets it, which I don't need).

This is one of my first Windows projects (or at least, only Windows and definitely only .NET) and I'm much more used to doing this sort of thing for *nix where I would use fork and then exec in the child, then wait for the child to terminate. But I have no idea where to even start looking to do something like this.

Oh, and I'm pretty sure I'm stuck in .NET because I need read access to the registry to complete this project and .NET's registry access is absolutely amazing (in my opinion, I don't have anything to compare it to).

Thanks.

like image 758
seanr8 Avatar asked Jul 19 '13 00:07

seanr8


3 Answers

You can use the Process class. It lets you specify some options about how you want to execute it, and also provides a method which waits the process to exit before executing the next statement.

look at this link (the msdn reference): http://msdn.microsoft.com/fr-fr/library/system.diagnostics.process.aspx

basically what you can do is:

 Process p;
 // some code to initialize it, like p = startProcessWithoutOutput(path, args, true);

 p.WaitForExit();

an example of initializing the process (that's just some code I used once somewhere):

    private Process startProcessWithOutput(string command, string args, bool showWindow)
    {
        Process p = new Process();
        p.StartInfo = new ProcessStartInfo(command, args);
        p.StartInfo.RedirectStandardOutput = false;
        p.StartInfo.RedirectStandardError = true;
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.CreateNoWindow = !showWindow;
        p.ErrorDataReceived += (s, a) => addLogLine(a.Data);
        p.Start();
        p.BeginErrorReadLine();

        return p;
    }

as you can see in this code you can also do some output redirection, error redirection.... If you dig in the class I think you'll find quite quickly what you need.

like image 75
ppetrov Avatar answered Sep 30 '22 01:09

ppetrov


var p = System.Diagnostics.Process.Start("notepad");
p.WaitForExit();
like image 23
I4V Avatar answered Sep 30 '22 01:09

I4V


You can use the Process class to start external processes. It will let you start arbitrary programs

http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx

like image 36
TGH Avatar answered Sep 30 '22 01:09

TGH