async Task OnExecuteDotNetCoreCommand(ProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration, ExecutionCommand executionCommand)
        {
            bool externalConsole = false;
            bool pauseConsole    = false;

            var dotNetCoreExecutionCommand = executionCommand as DotNetCoreExecutionCommand;

            if (dotNetCoreExecutionCommand != null)
            {
                externalConsole = dotNetCoreExecutionCommand.ExternalConsole;
                pauseConsole    = dotNetCoreExecutionCommand.PauseConsoleOutput;
            }

            OperationConsole console = externalConsole ? context.ExternalConsoleFactory.CreateConsole(!pauseConsole, monitor.CancellationToken)
                                : context.ConsoleFactory.CreateConsole(OperationConsoleFactory.CreateConsoleOptions.Default.WithTitle(Project.Name), monitor.CancellationToken);

            using (console) {
                ProcessAsyncOperation asyncOp = context.ExecutionHandler.Execute(executionCommand, console);

                try {
                    using (var stopper = monitor.CancellationToken.Register(asyncOp.Cancel))
                        await asyncOp.Task;

                    monitor.Log.WriteLine(GettextCatalog.GetString("The application exited with code: {0}", asyncOp.ExitCode));
                } catch (OperationCanceledException) {
                }
            }
        }
        protected override bool OnBuild(ProgressMonitor monitor, DeployContext ctx)
        {
            string           consMsg;
            OperationConsole cons;

            if (ExternalConsole)
            {
                cons    = ExternalConsoleFactory.Instance.CreateConsole(CloseConsoleWhenDone, monitor.CancellationToken);
                consMsg = GettextCatalog.GetString("(in external terminal)");
            }
            else
            {
                cons    = new MonitorConsole(monitor);
                consMsg = "";
            }

            monitor.Log.WriteLine(GettextCatalog.GetString("Executing: {0} {1} {2}", Command, Arguments, consMsg));
            ProcessAsyncOperation process = Runtime.ProcessService.StartConsoleProcess(Command, Arguments, workingDirectory, cons);

            process.Task.Wait();

            if (cons is MonitorConsole)
            {
                ((MonitorConsole)cons).Dispose();
            }
            return(true);
        }
Пример #3
0
            void StartProcess(SoftDebuggerStartInfo info)
            {
                if (string.IsNullOrEmpty(info.Command))
                {
                    return;
                }

                if (info.UseExternalConsole)
                {
                    usingExternalConsole = true;
                    var console = ExternalConsoleFactory.Instance.CreateConsole(info.CloseExternalConsoleOnExit);
                    process = Runtime.ProcessService.StartConsoleProcess(
                        info.Command, info.Arguments, info.WorkingDirectory, console, info.EnvironmentVariables);
                }
                else
                {
                    var psi = new ProcessStartInfo(info.Command, info.Arguments)
                    {
                        WorkingDirectory = info.WorkingDirectory,
                        UseShellExecute  = false
                    };
                    foreach (KeyValuePair <string, string> kvp in info.EnvironmentVariables)
                    {
                        psi.EnvironmentVariables [kvp.Key] = kvp.Value;
                    }

                    process = Runtime.ProcessService.StartProcess(psi, ProcessOutput, ProcessError, null).ProcessAsyncOperation;
                }
            }
Пример #4
0
        protected async override Task OnExecute(ProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration, SolutionItemRunConfiguration runConfiguration)
        {
            ProjectConfiguration conf = (ProjectConfiguration)GetConfiguration(configuration);

            monitor.Log.WriteLine(GettextCatalog.GetString("Running {0} ...", FileName));

            OperationConsole console = conf.ExternalConsole
                                ? context.ExternalConsoleFactory.CreateConsole(!conf.PauseConsoleOutput, monitor.CancellationToken)
                                                                                   : context.ConsoleFactory.CreateConsole(
                OperationConsoleFactory.CreateConsoleOptions.Default.WithTitle(Path.GetFileName(FileName)), monitor.CancellationToken);

            try {
                try {
                    ExecutionCommand executionCommand = CreateExecutionCommand(configuration, conf);

                    if (!context.ExecutionHandler.CanExecute(executionCommand))
                    {
                        monitor.ReportError(GettextCatalog.GetString("Can not execute \"{0}\". The selected execution mode is not supported for .NET projects.", FileName), null);
                        return;
                    }

                    ProcessAsyncOperation asyncOp = context.ExecutionHandler.Execute(executionCommand, console);
                    using (var stopper = monitor.CancellationToken.Register(asyncOp.Cancel)) {
                        await asyncOp.Task;
                    }

                    monitor.Log.WriteLine(GettextCatalog.GetString("The application exited with code: {0}", asyncOp.ExitCode));
                } finally {
                    console.Dispose();
                }
            } catch (Exception ex) {
                LoggingService.LogError(string.Format("Cannot execute \"{0}\"", FileName), ex);
                monitor.ReportError(GettextCatalog.GetString("Cannot execute \"{0}\"", FileName), ex);
            }
        }
Пример #5
0
 public ProcessAdapter(ProcessAsyncOperation oper, string name)
 {
     this.oper = oper;
     this.name = name;
     oper.Task.ContinueWith(t => {
         if (Exited != null)
         {
             Exited(this, EventArgs.Empty);
         }
     }, Runtime.MainTaskScheduler);
 }
Пример #6
0
        async Task PrivateStart()
        {
            var token = restartTokenSource.Token;

            startedSource        = new TaskCompletionSource <bool> ();
            communicationManager = new SocketCommunicationManager();
            var endPoint = communicationManager.HostServer(new IPEndPoint(IPAddress.Loopback, 0));

            communicationManager.AcceptClientAsync().Ignore();
            vsTestConsoleExeProcess = StartVsTestConsoleExe(endPoint.Port);
            vsTestConsoleExeProcess.Task.ContinueWith(delegate {
                VsTestProcessExited(vsTestConsoleExeProcess);
            }).Ignore();
            var sw = Stopwatch.StartNew();

            if (!await Task.Run(() => {
                while (!token.IsCancellationRequested)
                {
                    if (communicationManager.WaitForClientConnection(100))
                    {
                        return(true);
                    }
                    if (clientConnectionTimeOut < sw.ElapsedMilliseconds)
                    {
                        return(false);
                    }
                }
                return(false);
            }))
            {
                sw.Stop();
                throw new TimeoutException("vstest.console failed to connect.");
            }
            sw.Stop();
            if (token.IsCancellationRequested)
            {
                return;
            }

            messageProcessingThread =
                new Thread(ReceiveMessages)
            {
                IsBackground = true
            };
            messageProcessingThread.Start(token);
            var timeoutDelay = Task.Delay(clientConnectionTimeOut);

            if (await Task.WhenAny(startedSource.Task, timeoutDelay) == timeoutDelay)
            {
                throw new TimeoutException("vstest.console failed to respond.");
            }
        }
Пример #7
0
        public override void Dispose()
        {
            if (console != null && !console.IsCompleted)
            {
                console.Cancel();
                console = null;
            }

            if (thread != null)
            {
                thread.Abort();
            }
        }
        BuildResult CreateBuildResult(ProcessAsyncOperation operation, ConsoleWrapper console)
        {
            if (operation.Task.IsFaulted || operation.ExitCode != 0)
            {
                BuildResult result = console.GetBuildResult(project);
                if (!(result.HasErrors || result.HasWarnings))
                {
                    result.AddError(GettextCatalog.GetString("Build failed. Please see the Build Output for more details."));
                }
                return(result);
            }

            return(console.GetBuildResult(project));
        }
 void ReportOutcome(
     ProcessAsyncOperation operation,
     ProgressMonitor progressMonitor,
     ProgressMonitorStatusMessage progressMessage)
 {
     if (!operation.Task.IsFaulted && operation.ExitCode == 0)
     {
         progressMonitor.ReportSuccess(progressMessage.Success);
     }
     else
     {
         progressMonitor.ReportError(progressMessage.Error, null);
         progressMonitor.ShowPackageConsole();
     }
 }
        void RunDotNetCoreTest(string projectDirectory)
        {
            string arguments = String.Format(@"test --port {0} --parentProcessId {1} --no-build",
                                             testServer.Port,
                                             Process.GetCurrentProcess().Id);

            DnxOutputPad.WriteText(GettextCatalog.GetString("Starting test discovery..."));
            DnxOutputPad.WriteText(String.Format("{0} {1}", DnxServices.ProjectService.CurrentDotNetRuntimePath, arguments));

            dotNetTestOperation = Runtime.ProcessService.StartConsoleProcess(
                DnxServices.ProjectService.CurrentDotNetRuntimePath,
                arguments,
                projectDirectory,
                new DotNetCoreOutputOperationConsole(),
                null,
                DotNetTestProcessExited);
        }
        public Task <BuildResult> BuildAsnc(DotNetProjectConfiguration config)
        {
            var console = new ConsoleWrapper(monitor);

            ProcessAsyncOperation operation = Runtime.ProcessService.StartConsoleProcess(
                DnxServices.ProjectService.CurrentDotNetRuntimePath,
                String.Format("build --configuration {0} --no-dependencies", config.Name),
                project.BaseDirectory,
                console,
                null,
                (sender, e) => { }
                );

            return(operation.Task.ContinueWith(t => {
                return CreateBuildResult(operation, console);
            }));
        }
Пример #12
0
        protected async override Task DoExecute(ProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration)
        {
            CProjectConfiguration conf = (CProjectConfiguration)GetConfiguration(configuration);
            bool             pause     = conf.PauseConsoleOutput;
            OperationConsole console;

            if (conf.CompileTarget != CBinding.CompileTarget.Bin)
            {
                MessageService.ShowMessage("Compile target is not an executable!");
                return;
            }

            monitor.Log.WriteLine("Running project...");

            if (conf.ExternalConsole)
            {
                console = context.ExternalConsoleFactory.CreateConsole(!pause, monitor.CancellationToken);
            }
            else
            {
                console = context.ConsoleFactory.CreateConsole(monitor.CancellationToken);
            }

            try {
                ExecutionCommand cmd = CreateExecutionCommand(conf);
                if (!context.ExecutionHandler.CanExecute(cmd))
                {
                    monitor.ReportError("Cannot execute \"" + conf.Output + "\". The selected execution mode is not supported for C projects.", null);
                    return;
                }

                ProcessAsyncOperation op = context.ExecutionHandler.Execute(cmd, console);
                using (var t = monitor.CancellationToken.Register(op.Cancel))
                    await op.Task;

                monitor.Log.WriteLine("The operation exited with code: {0}", op.ExitCode);
            } catch (Exception ex) {
                LoggingService.LogError(string.Format("Cannot execute \"{0}\"", conf.Output), ex);
                monitor.ReportError("Cannot execute \"" + conf.Output + "\"", ex);
            } finally {
                console.Dispose();
            }
        }
Пример #13
0
            void EndProcess()
            {
                if (process == null)
                {
                    return;
                }

                var p = process;

                process = null;

                if (usingExternalConsole || p.IsCompleted)
                {
                    return;
                }

                try {
                    p.Cancel();
                } catch {}
            }
Пример #14
0
        public void Stop()
        {
            lock (_processLock)
            {
                if (_stopped)
                {
                    return;
                }

                _stopped = true;

                if (_designTimeHostOperation != null)
                {
                    _logger.LogInformation("Shutting down DesignTimeHost");

                    _designTimeHostOperation.Cancel();
                    _designTimeHostOperation = null;
                }
            }
        }
        public void Dispose()
        {
            IsRunning = false;

            try {
                if (shutdownTimer != null)
                {
                    shutdownTimer.Stop();
                    shutdownTimer.Elapsed -= ShutdownTimerElapsed;
                    shutdownTimer.Dispose();
                    shutdownTimer = null;
                }
            } catch (Exception ex) {
                LoggingService.LogError("Test loader dispose error.", ex);
            }

            try {
                if (testServer != null)
                {
                    testServer.Dispose();
                    testServer = null;
                }
            } catch (Exception ex) {
                LoggingService.LogError("Test loader dispose error.", ex);
            }

            try {
                if (dotNetTestOperation != null)
                {
                    if (!dotNetTestOperation.IsCompleted)
                    {
                        dotNetTestOperation.Cancel();
                    }
                    dotNetTestOperation = null;
                }
            } catch (Exception ex) {
                LoggingService.LogError("Test loader dispose error.", ex);
            }
        }
Пример #16
0
        protected async override void Run()
        {
            var executionTarger = IdeApp.Workspace.ActiveExecutionTarget as IoTExecutionTarget;
            var server          = executionTarger?.ServerInteractive?.CurrentServer;

            if (server == null)
            {
                return;
            }

            tracer.Info($"Opening SSH with {server.FullName}...");

            ProcessAsyncOperation oper = null;

            bool pauseExternalConsole = false;

            var cs      = new CancellationTokenSource();
            var monitor = new ProgressMonitor(cs);

            try {
                var console = ExternalConsoleFactory.Instance.CreateConsole(!pauseExternalConsole, monitor.CancellationToken);
                oper = Runtime.ProcessService.StartConsoleProcess("ssh", $"{server.Username}@{server.IpAddress.ToString ()}",
                                                                  new FilePath("$HOME"), console, null);

                var stopper = monitor.CancellationToken.Register(oper.Cancel);
                await oper.Task;
                stopper.Dispose();

                if (oper.ExitCode != 0)
                {
                    var msgError = $"Custom command failed (exit code: {oper.ExitCode});";
                    tracer.Error(msgError);
                    monitor.ReportError(msgError, null);
                }
            } catch (Exception ex) {
                LoggingService.LogError(ex.ToString());
            }
        }
Пример #17
0
        protected async override Task OnExecute(ProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration)
        {
            var config = GetConfiguration(configuration) as DotNetProjectConfiguration;

            DotNetCoreExecutionCommand executionCommand = CreateDotNetCoreExecutionCommand(configuration, config);

            if (context.ExecutionTarget != null)
            {
                executionCommand.Target = context.ExecutionTarget;
            }

            executionCommand.Initialize();

            if (CanDebug(executionCommand, context))
            {
                await base.OnExecute(monitor, context, configuration);

                return;
            }

            monitor.Log.WriteLine(GettextCatalog.GetString("Running {0} ...", Name));

            OperationConsole console = CreateConsole(config, context, monitor);

            try {
                try {
                    ProcessAsyncOperation asyncOp = Execute(executionCommand, console);
                    await asyncOp.Task;

                    monitor.Log.WriteLine(GettextCatalog.GetString("The application exited with code: {0}", asyncOp.ExitCode));
                } finally {
                    console.Dispose();
                }
            } catch (Exception ex) {
                LoggingService.LogError(string.Format("Cannot execute \"{0}\"", Name), ex);
                monitor.ReportError(GettextCatalog.GetString("Cannot execute \"{0}\"", Name), ex);
            }
        }
Пример #18
0
        int StartCustomTestHost(TestProcessStartInfo startInfo, TestContext currentTestContext)
        {
            OperationConsole console = currentTestContext.ExecutionContext.ConsoleFactory.CreateConsole(
                OperationConsoleFactory.CreateConsoleOptions.Default.WithTitle(GettextCatalog.GetString("Unit Tests")));

            var command = new DotNetCoreExecutionCommand(
                startInfo.WorkingDirectory,
                startInfo.FileName,
                startInfo.Arguments
                );

            command.Command = startInfo.FileName;
            command.EnvironmentVariables = startInfo.EnvironmentVariables;

            debugOperation = currentTestContext.ExecutionContext.ExecutionHandler.Execute(command, console);

            // Returns the IDE process id which is incorrect. This should be the
            // custom test host process. The VSCodeDebuggerSession does not return
            // the correct process id. If it did the process is not available
            // immediately since it takes some time for it to start so a wait
            // would be needed here.
            return(Process.GetCurrentProcess().Id);
        }
        int StartCustomTestHost(TestProcessStartInfo startInfo, TestContext currentTestContext)
        {
            OperationConsole console = currentTestContext.ExecutionContext.ConsoleFactory.CreateConsole(
                OperationConsoleFactory.CreateConsoleOptions.Default.WithTitle(GettextCatalog.GetString("Unit Tests")));

            var command = new DotNetCoreExecutionCommand(
                startInfo.WorkingDirectory,
                startInfo.FileName,
                startInfo.Arguments
                );

            command.Command              = startInfo.FileName;
            command.Arguments            = startInfo.Arguments;
            command.EnvironmentVariables = startInfo.EnvironmentVariables;

            debugOperation = currentTestContext.ExecutionContext.ExecutionHandler.Execute(command, console);

            // Returns the IDE process id which is incorrect. This should be the
            // custom test host process. The VSCodeDebuggerSession does not return
            // the correct process id. If it did the process is not available
            // immediately since it takes some time for it to start so a wait
            // would be needed here. Note that returning process id of 1 for .NET
            // Core SDK versions 1.0 does not work the debugger never starts.
            var latestVersion = DotNetCoreSdk.Versions.FirstOrDefault();

            if (latestVersion == null || latestVersion.Major < 2)
            {
                return(Process.GetCurrentProcess().Id);
            }

            //This is horrible hack...
            //VSTest wants us to send it PID of process our debugger just started so it can kill it when tests are finished
            //VSCode debug protocol doesn't give us PID of debugee
            //But we must give VSTest valid PID or it won't work... In past we gave it IDE PID, but with new versions of
            //VSTest it means it will kill our IDE... Hence give it PID 1 and hope it won't kill it.
            return(1);
        }
Пример #20
0
        public async Task <ITaskRunnerCommandResult> ExecuteCommand(ITaskRunnerCommand command)
        {
            using (var monitor = new TaskRunnerProgressMonitor(outputProgressMonitor)) {
                monitor.Log.WriteLine(command.ToCommandLine());

                var result = Runtime.ProcessService.StartConsoleProcess(
                    command.Executable,
                    command.GetFullArgs(),
                    command.WorkingDirectory,
                    monitor.Console);

                currentOperation = result;

                await result.Task;

                currentOperation = null;

                return(new TaskRunnerCommandResult {
                    StandardOutput = monitor.GetStandardOutputText(),
                    StandardError = monitor.GetStandardErrorText(),
                    ExitCode = result.ExitCode
                });
            }
        }
Пример #21
0
        public void CancelTestRun()
        {
            if (IsRunningTests)
            {
                try {
                    communicationManager.SendMessage(MessageType.CancelTestRun);
                } catch (Exception ex) {
                    LoggingService.LogError("CancelTestRun error.", ex);
                }

                try {
                    if (debugOperation != null)
                    {
                        if (!debugOperation.IsCompleted)
                        {
                            debugOperation.Cancel();
                        }
                        debugOperation = null;
                    }
                } catch (Exception ex) {
                    LoggingService.LogError("CancelTestRun error.", ex);
                }
            }
        }
Пример #22
0
 void VsTestProcessExited(ProcessAsyncOperation process)
 {
     LoggingService.LogError("vstest.console.exe exited. Exit code: {0}", process.ExitCode);
     Restart();
 }
Пример #23
0
        public async Task <bool> Execute(ProgressMonitor monitor, WorkspaceObject entry, ExecutionContext context,
                                         ConfigurationSelector configuration)
        {
            ProcessExecutionCommand cmd = CreateExecutionCommand(entry, configuration);

            monitor.Log.WriteLine(GettextCatalog.GetString("Executing: {0} {1}", cmd.Command, cmd.Arguments));

            if (!Directory.Exists(cmd.WorkingDirectory))
            {
                monitor.ReportError(GettextCatalog.GetString("Custom command working directory does not exist"), null);
                return(false);
            }

            ProcessAsyncOperation oper    = null;
            OperationConsole      console = null;
            var result = true;

            try {
                if (context != null)
                {
                    if (externalConsole)
                    {
                        console = context.ExternalConsoleFactory.CreateConsole(!pauseExternalConsole, monitor.CancellationToken);
                    }
                    else
                    {
                        console = context.ConsoleFactory.CreateConsole(monitor.CancellationToken);
                    }
                    oper = context.ExecutionHandler.Execute(cmd, console);
                }
                else
                {
                    if (externalConsole)
                    {
                        console = ExternalConsoleFactory.Instance.CreateConsole(!pauseExternalConsole, monitor.CancellationToken);
                        oper    = Runtime.ProcessService.StartConsoleProcess(cmd.Command, cmd.Arguments,
                                                                             cmd.WorkingDirectory, console, null);
                    }
                    else
                    {
                        oper = Runtime.ProcessService.StartProcess(cmd.Command, cmd.Arguments,
                                                                   cmd.WorkingDirectory, monitor.Log, monitor.Log, null, false).ProcessAsyncOperation;
                    }
                }

                using (var stopper = monitor.CancellationToken.Register(oper.Cancel)) {
                    await oper.Task;
                }

                if (oper.ExitCode != 0)
                {
                    monitor.ReportError(GettextCatalog.GetString("Custom command failed (exit code: {0})", oper.ExitCode), null);
                }
            } catch (Win32Exception w32ex) {
                monitor.ReportError(GettextCatalog.GetString("Failed to execute custom command '{0}': {1}",
                                                             cmd.Command, w32ex.Message), null);
                return(false);
            } catch (Exception ex) {
                LoggingService.LogError("Command execution failed", ex);
                throw new UserException(GettextCatalog.GetString("Command execution failed: {0}", ex.Message));
            } finally {
                result = oper != null && oper.ExitCode == 0;
                if (console != null)
                {
                    console.Dispose();
                }
            }
            return(result);
        }
Пример #24
0
        public void Start(string hostId, Action <int> onConnected)
        {
            lock (_processLock)
            {
                if (_stopped)
                {
                    return;
                }

                int port = GetFreePort();

                string arguments = string.Format(@"projectmodel-server --port {0} --host-pid {1} --host-name {2}",
                                                 port,
                                                 Process.GetCurrentProcess().Id,
                                                 hostId);

                _logger.LogVerbose(_paths.DotNet + " " + arguments);

                _designTimeHostOperation = Runtime.ProcessService.StartConsoleProcess(
                    _paths.DotNet,
                    arguments,
                    null,
                    new DotNetCoreOutputOperationConsole(),
                    null,
                    (sender, e) => {
                    _logger.LogWarning("Design time host process ended");

                    Start(hostId, onConnected);
                }
                    );

                // Wait a little bit for it to conncet before firing the callback
                using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {
                    var t1         = DateTime.UtcNow;
                    var dthTimeout = TimeSpan.FromSeconds(10);
                    while (!socket.Connected && DateTime.UtcNow - t1 < dthTimeout)
                    {
                        Thread.Sleep(500);
                        try
                        {
                            socket.Connect(new IPEndPoint(IPAddress.Loopback, port));
                        }
                        catch (SocketException)
                        {
                            // this happens when the DTH isn't listening yet
                        }
                    }

                    if (!socket.Connected)
                    {
                        // reached timeout
                        _logger.LogError("Failed to launch DesignTimeHost in a timely fashion.");
                        return;
                    }
                }

                if (_designTimeHostOperation.IsCompleted)
                {
                    // REVIEW: Should we quit here or retry?
                    _logger.LogError(string.Format("Failed to launch DesignTimeHost. Process exited with code {0}.", _designTimeHostOperation.ExitCode));
                    return;
                }

                _logger.LogInformation(string.Format("Running DesignTimeHost on port {0}, with PID {1}", port, _designTimeHostOperation.ProcessId));

                onConnected(port);
            }
        }
Пример #25
0
        protected override void OnRun(DebuggerStartInfo startInfo)
        {
            lock (gdbLock) {
                // Create a script to be run in a terminal
                string script      = Path.GetTempFileName();
                string ttyfile     = Path.GetTempFileName();
                string ttyfileDone = ttyfile + "_done";
                string tty;

                try {
                    File.WriteAllText(script, "tty > " + ttyfile + "\ntouch " + ttyfileDone + "\nsleep 10000d");
                    Mono.Unix.Native.Syscall.chmod(script, FilePermissions.ALLPERMS);

                    console = Runtime.ProcessService.StartConsoleProcess(script, "", ".", ExternalConsoleFactory.Instance.CreateConsole(true), null);
                    DateTime tim = DateTime.Now;
                    while (!File.Exists(ttyfileDone))
                    {
                        System.Threading.Thread.Sleep(100);
                        if ((DateTime.Now - tim).TotalSeconds > 10)
                        {
                            throw new InvalidOperationException("Console could not be created.");
                        }
                    }
                    tty = File.ReadAllText(ttyfile).Trim(' ', '\n');
                } finally {
                    try {
                        if (File.Exists(script))
                        {
                            File.Delete(script);
                        }
                        if (File.Exists(ttyfile))
                        {
                            File.Delete(ttyfile);
                        }
                        if (File.Exists(ttyfileDone))
                        {
                            File.Delete(ttyfileDone);
                        }
                    } catch {
                        // Ignore
                    }
                }

                StartGdb();

                // Initialize the terminal
                RunCommand("-inferior-tty-set", Escape(tty));

                try {
                    RunCommand("-file-exec-and-symbols", Escape(startInfo.Command));
                } catch {
                    FireTargetEvent(TargetEventType.TargetExited, null);
                    throw;
                }

                RunCommand("-environment-cd", Escape(startInfo.WorkingDirectory));

                // Set inferior arguments
                if (!string.IsNullOrEmpty(startInfo.Arguments))
                {
                    RunCommand("-exec-arguments", startInfo.Arguments);
                }

                if (startInfo.EnvironmentVariables != null)
                {
                    foreach (var v in startInfo.EnvironmentVariables)
                    {
                        RunCommand("-gdb-set", "environment", v.Key, v.Value);
                    }
                }

                currentProcessName = startInfo.Command + " " + startInfo.Arguments;

                CheckIsMonoProcess();
                OnStarted();

                RunCommand("-exec-run");
            }
        }