1

I have a c# application currently running from the Terminal. It opens up a new terminal to execute a certain command then closes that terminal. I'm wondering if I can just execute this command in the terminal that is currently opened, instead of opening a new one. My code to execute the command is as follows.

        Process proc = new System.Diagnostics.Process();
        proc.StartInfo.WorkingDirectory = @"MyDirectory";
        proc.StartInfo.FileName = @"/usr/bash";
        proc.StartInfo.Arguments = command;
        proc.StartInfo.UseShellExecute = false;
        proc.StartInfo.RedirectStandardOutput = true;
        proc.Start();

How would I rewrite this without opening a new terminal?

user2748943
  • 533
  • 2
  • 9
  • 20
  • You can hide the new terminal, but it's always going to run in its own process. Unless you emulate the shell commands yourself. – VoidStar Aug 11 '15 at 17:52
  • Since you are using 'UseShellExecute = false' you can just use 'system' to execute your 'command', unless you are actually doing something with the redirected out. If that is the case, why are you shelling to bash to run 'command'? – SushiHangover Aug 11 '15 at 20:29
  • 1
    In a Windows console app, simply setting UseShellExecute - w/o redirection or anything else - worked for me. See [here](https://stackoverflow.com/a/47781912/63209). – Paul Dec 12 '17 at 21:40

2 Answers2

1

As far as I know, no - but you can use the code

startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;

to make it so that the window does not pop up. Then in your normal terminal you can use print to update the user with a message like "Running Script..."

Nefariis
  • 3,451
  • 10
  • 34
  • 52
  • Thanks for you're answer. It's not something that will be used by a user, so it's not a huge deal if another terminal is generated. It just seemed weird to have a terminal open another terminal. But I've had this issue before on a prior project and you're solution would help me if I had to do something like that again. Thank you – user2748943 Aug 11 '15 at 18:31
0

You can directly use libc system vs. the Diagnostics.Process and the redirection pipes (which just wrap the libc functions):

using System;
using System.Runtime.InteropServices;

namespace ShellMe
{
    class MainClass
    {
        [DllImport ("libc")]
        private static extern int system (string exec);

        public static void Main (string[] args)
        {
            system("YourCommand2Run");   // blocking, you are in a shell so same rules apply
            system("YourCommand2Run &"); // non-blocking
        }
    }
}
SushiHangover
  • 73,120
  • 10
  • 106
  • 165