5

I've some troubles with running processes and passing args to them. I know how to run process with some args

ProcessStartInfo psi = new ProcessStartInfo("cmd.exe", "/c something");  
Process p = Process.Start(psi)

The problem is that after script is executed process is terminated. That's why there is "/c"

But I'm running multiple scripts and I would like to run them in one process ("cmd.exe") not to start new process every time.

Is there some solutions for it ?

I hope somebody understand what I'm talking about ;)

DaveShaw
  • 52,123
  • 16
  • 112
  • 141
kosa
  • 51
  • 1
  • 2

2 Answers2

10

I recommend you utilize a batch file to script the execution of your executables and call your batch file instead. Or, you can do this -

    Process p = new Process();
    ProcessStartInfo info = new ProcessStartInfo();
    info.FileName = "cmd.exe";
    info.RedirectStandardInput = true;
    info.UseShellExecute = false;

    p.StartInfo = info;
    p.Start();

    using (StreamWriter sw = new StreamWriter(p.StandardInput))
    {
        if (sw.BaseStream.CanWrite)
        {
            sw.WriteLine("mysql -u root -p");
            sw.WriteLine("mypassword");
            sw.WriteLine("use mydb;");
        }
    }
Community
  • 1
  • 1
  • you dont really need to do the streamwriter writeline. You can just call p.startinfo.filename = "cmd.exe"; p.startinfo.Arguments = "blah"; p.start(); p.waitforexit(); p.close(); – Grant Jul 19 '11 at 21:18
  • Thanks it was very helpful but I've still some problems. – kosa Jul 20 '11 at 18:23
  • I try to create Process and start it in constructor of the class and then call method from this class when I run scripts. But when I start process it exited in the same moment – kosa Jul 20 '11 at 18:24
  • @kosa: Can you post your code to pastebin and provide me the link? –  Jul 20 '11 at 18:47
  • You forgot to say new Process. –  Jul 20 '11 at 19:44
  • sorry, i forgot to copy new Process and new ProcessStartInfo – kosa Jul 20 '11 at 19:52
0

It sounds like you ought to investigate redirecting the standard input - be sure to also set psi.UseShellExecute to false. You'll probably also want to redirect standard output, so you can have some way of knowing what your child process is doing.

Read more about redirection here.

Ben
  • 6,023
  • 1
  • 25
  • 40