Kill() public method

Stops the associated process immediately.
public Kill ( ) : void
return void
Esempio n. 1
1
        private MemoryStream GetThumbnailFromProcess(Process p, ref int width, ref int height)
        {
            Debug("Starting ffmpeg");
              using (var thumb = new MemoryStream()) {
            var pump = new StreamPump(p.StandardOutput.BaseStream, thumb, null, 4096);
            if (!p.WaitForExit(20000)) {
              p.Kill();
              throw new ArgumentException("ffmpeg timed out");
            }
            if (p.ExitCode != 0) {
              throw new ArgumentException("ffmpeg does not understand the stream");
            }
            Debug("Done ffmpeg");
            if (!pump.Wait(2000)) {
              throw new ArgumentException("stream reading timed out");
            }
            if (thumb.Length == 0) {
              throw new ArgumentException("ffmpeg did not produce a result");
            }

            using (var img = Image.FromStream(thumb)) {
              using (var scaled = ThumbnailMaker.ResizeImage(img, ref width, ref height)) {
            var rv = new MemoryStream();
            try {
              scaled.Save(rv, ImageFormat.Jpeg);
              return rv;
            }
            catch (Exception) {
              rv.Dispose();
              throw;
            }
              }
            }
              }
        }
Esempio n. 2
0
        /// <summary>
        /// Hybrid replay mode uses windbg
        /// </summary>
        protected void _StartDebuggerHybridReplay()
        {
            if (_debuggerProcess == null || _debuggerProcess.HasExited)
            {
                using (var p = System.Diagnostics.Process.GetCurrentProcess())
                {
                    _debuggerChannelName = "PeachCore_" + p.Id + "_" + (ipcChannelCount++);
                }

                // Launch the server process
                _debuggerProcess = new System.Diagnostics.Process();
                _debuggerProcess.StartInfo.CreateNoWindow  = true;
                _debuggerProcess.StartInfo.UseShellExecute = false;
                _debuggerProcess.StartInfo.Arguments       = _debuggerChannelName;
                _debuggerProcess.StartInfo.FileName        = Path.Combine(
                    Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                    "Peach.Core.WindowsDebugInstance.exe");
                _debuggerProcess.Start();

                // Let the process get started.
                Thread.Sleep(2000);
            }

            // Try and create instance over IPC.  We will continue trying for 1 minute.

            DateTime startTimer = DateTime.Now;

            while (true)
            {
                try
                {
                    _debugger = (DebuggerInstance)Activator.GetObject(typeof(DebuggerInstance),
                                                                      "ipc://" + _debuggerChannelName + "/DebuggerInstance");

                    _debugger.commandLine            = _commandLine;
                    _debugger.processName            = _processName;
                    _debugger.kernelConnectionString = _kernelConnectionString;
                    _debugger.service     = _service;
                    _debugger.symbolsPath = _symbolsPath;
                    _debugger.startOnCall = _startOnCall;
                    _debugger.ignoreFirstChanceGuardPage  = _ignoreFirstChanceGuardPage;
                    _debugger.ignoreSecondChanceGuardPage = _ignoreSecondChanceGuardPage;
                    _debugger.noCpuKill  = _noCpuKill;
                    _debugger.winDbgPath = _winDbgPath;

                    break;
                }
                catch
                {
                    if ((DateTime.Now - startTimer).Minutes >= 1)
                    {
                        _debuggerProcess.Kill();
                        _debuggerProcess = null;
                        throw;
                    }
                }
            }

            _debugger.StartDebugger();
        }
Esempio n. 3
0
 void OnDestroy()
 {
     if (process_ != null && !process_.HasExited)
     {
         process_.Kill();
         process_.Dispose();
     }
 }
Esempio n. 4
0
 void OnApplicationQuit()
 {
     if (process_ != null && !process_.HasExited)
     {
         process_.Kill();
         process_.Dispose();
     }
 }
Esempio n. 5
0
 private void TimeoutHandler(object sender, ElapsedEventArgs e)
 {
     if (Procs != null)
     {
         if (!Procs.HasExited)
         {
             Procs.Kill();
         }
     }
 }
Esempio n. 6
0
 public virtual void  shutdown()
 {
     try {
         // [PM] 3.12.0 this can barf (as can process.HasExited) if
         // the process did not start e.g., the path was not found.
         process.Kill();
     }
     catch (System.Exception) {
         // ignore all errors
     }
 }
Esempio n. 7
0
    void OnDestroy()
    {
        stop = true;

        if (client != null)
        {
            client.Close();
        }
        if (decoderProcess != null)
        {
            decoderProcess.Kill();
        }
    }
Esempio n. 8
0
        public bool WaitForExit(int milliseconds)
        {
            if (_process.WaitForExit(milliseconds))
            {
                return(true);
            }

            if (HasExited)
            {
                _process.Kill();
            }
            return(false);
        }
        private void beginInArcadeMode(ref GameConfiguration gameConfig)
        {
            Boolean closed = true;
            Boolean stopRunner = false;
            Process game = new Process();
            Process joyToKey = new Process();
            GlobalMouseKeyboard globalMouseKeyboard = new GlobalMouseKeyboard();

            runJoyToKey(ref gameConfig);

            while (!stopRunner)
            {
                if (globalMouseKeyboard.F2IsPressed)
                {
                    //restart the game
                    game.Kill();
                    closed = true;
                    globalMouseKeyboard.F2IsPressed = false;
                }

                if (globalMouseKeyboard.F4IsPressed)
                {
                    //end arcade mode
                    game.Kill();
                    stopRunner = true;
                    globalMouseKeyboard.Dispose();
                }

                if (closed)
                {
                    if (gameConfig.HideMouse)
                        Cursor.Position = new Point(2000, 2000); //work around
                        //another work around, set the cursor graphic to a transparent one, http://forums.whirlpool.net.au/archive/1172326

                    ProcessStartInfo psi = new ProcessStartInfo(gameConfig.GamePath);
                    if (gameConfig.FullScreen)
                        psi.WindowStyle = ProcessWindowStyle.Maximized; //TODO: only maximizes fully if the taskbar is set to auto-hide
                    game = Process.Start(psi);

                    closed = false;
                }

                game.WaitForExit(100); //? to reduce cpu usage?

                if (game.HasExited)
                {
                    closed = true;
                }
            }
        }
Esempio n. 10
0
        public void t_Elapsed(object sender, ElapsedEventArgs e, Process p, string date)
        {
            Timer t = (Timer)sender;
            t.Stop();

            if (p.ProcessName == "java")
            {
                if (Utilities.scanProcess(p))
                {
                    if (AntiPwny.PreventionMode)
                    {
                        builder.Clear();
                        builder.Append(p.ProcessName);
                        builder.Append(" Killed.");
                        p.Kill();

                        w.write(date, builder.ToString(), "Java Meterpreter");
                    }
                    else
                    {
                        builder.Clear();
                        builder.Append(p.ProcessName);
                        builder.Append(" memory contains java meterpreter signature.");

                        w.write(date, builder.ToString(), "Java Meterpreter Found");
                    }
                }
            }
            if (Utilities.scanProcess(p))
            {
                if (AntiPwny.PreventionMode)
                {
                    builder.Clear();
                    builder.Append(p.ProcessName);
                    builder.Append(" Killed.");
                    p.Kill();

                    w.write(date, builder.ToString(), "Meterpreter");
                }
                else
                {
                    builder.Clear();
                    builder.Append(p.ProcessName);
                    builder.Append(" memory contains meterpreter signature.");

                    w.write(date, builder.ToString(), "Meterpreter Found");
                }
            }
        }
Esempio n. 11
0
 /*外部プログラムjulisのプロセスを強制終了*/
 private void kill_julius_server()
 {
     //プロセスの強制終了
     julius_process.Kill();
     if (julius_process.HasExited)
     {
         Debug.Log("Kill julius server.");
     }
     else
     {
         julius_process.Kill();
     }
     julius_process.Close();
     julius_process.Dispose();
 }
Esempio n. 12
0
      public static async Task<bool> Execute(Params @params)
      {
         var arguments = string.Join(" ",
                                     string.Format("\"{0}\"", @params.SolutionPath),
                                     @params.Args,
                                     string.Format(MsBuildArgs,
                                                   @params.Configuration,
                                                   @params.Platform,
                                                   @params.Verbosity));
         var process = new Process
                       {
                          StartInfo = new ProcessStartInfo(MsBuildPath)
                                      {
                                         Arguments = arguments,
                                         CreateNoWindow = true,
                                         RedirectStandardOutput = true,
                                         UseShellExecute = false
                                      }
                       };
         process.OutputDataReceived += (sender, args) => @params.Callback(args.Data);
         process.Start();
         process.BeginOutputReadLine();
         while (!process.HasExited)
         {
            if (@params.CancellationToken.IsCancellationRequested)
            {
               process.Kill();
               return false;
            }

            await Task.Delay(50, @params.CancellationToken);
         }

         return process.ExitCode == 0;
      }
Esempio n. 13
0
        public static bool executeProcessWithParams(string stringPathToFileToExecute,string stringArguments,bool bShowCmdWindow, ref bool bCancelProcessExecution)
        {
            bCancelProcessExecution = false;
            try
            {
                Process pProcess = new Process();

                pProcess.StartInfo.Arguments = stringArguments;
                pProcess.StartInfo.FileName = stringPathToFileToExecute;
                if (bShowCmdWindow)
                    pProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
                else
                    pProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                pProcess.Start();
                while (! pProcess.HasExited)
                {
                    pProcess.Refresh();
                    Thread.Sleep(100);
                    Application.DoEvents();
                    if (bCancelProcessExecution)
                    {
                        pProcess.Kill();
                        MessageBox.Show("Process execution canceled");
                        return false;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
        }
Esempio n. 14
0
        public void LoginGmail()
        {
            string pipename = Process.GetCurrentProcess().Id.ToString() + "_login_gmail";

            var pipe = new NamedPipeServerStream(pipename, PipeDirection.InOut, 1);

            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo           = new ProcessStartInfo();
            process.StartInfo.FileName  = "3s_atc - browser.exe";
            process.StartInfo.Arguments = "https://www.google.com/gmail" + " " + pipename;
            process.Start();

            pipe.WaitForConnection();

            StreamReader reader = new StreamReader(pipe);

            string str = reader.ReadLine();

            if (!String.IsNullOrEmpty(str))
            {
                gmail_cookies  = DeserializeCefCookies(str);
                gmail_loggedin = true;
                MessageBox.Show("Logged in!", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            process.Kill();
        }
Esempio n. 15
0
        //**********************************************************************
        /// <summary>
        /// Open excel file, verify content contains or not contains given string.
        /// </summary>
        public static void VerifyExcelfileValues(LxScriptItem item)
        {
            string strPath     = item.getArgText();
            string strFileName = strPath.Substring(strPath.LastIndexOf("/") + 1, strPath.Length - strPath.LastIndexOf("/") - 1);
            string mark        = item.getArg3Text();       // flag=true, contains; flag=false, not contains.

            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
            startInfo.FileName  = "excel.exe";
            startInfo.Arguments = " " + strPath;
            System.Diagnostics.Process process = System.Diagnostics.Process.Start(startInfo);
            RepoItemInfo targetCellInfo        = new RepoItemInfo(repo.ExternalApp.FormExcel.TableEntityInfo.ParentFolder, "variableCell",
                                                                  repo.ExternalApp.FormExcel.TableEntityInfo.Path + "/row/cell[@text='" + item.getArg2Text() + "']",
                                                                  10000, null, System.Guid.NewGuid().ToString());


            Delay.Milliseconds(6000);
            bool bExists = targetCellInfo.Exists();

            process.Kill();
            if (mark.Equals("True"))
            {
                Validate.AreEqual(bExists, true);
            }
            else
            {
                Validate.AreEqual(bExists, false);
            }
        }
Esempio n. 16
0
 static void LineAssert(string line, string readLine, Process process)
 {
     if (line != readLine) {
         process.Kill();
         Assert.Fail("Expected \"{0}\", found \"{1}\".", line, readLine);
     }
 }
Esempio n. 17
0
    //実行終了時に外部プロセスが生きているなら自動終了させる
    void OnApplicationQuit()
    {
        if (!lunchTheServerProcess)
        {
            return;
        }

        if (wiimoteServerProcess.HasExited)
        {
            Debug.Log("外部プロセスは終了済みです");
            return;
        }

        //まだ外部プロセスが動いていれば終了させる。
        try {
            //メインウィンドウを閉じる
            wiimoteServerProcess.CloseMainWindow();
            //プロセスが終了するまで最大2秒待機する
            wiimoteServerProcess.WaitForExit(2);
            //プロセスが終了したか確認する
            if (wiimoteServerProcess.HasExited)
            {
                Debug.Log("外部プロセスが終了しました");
            }
            else
            {
                Debug.LogError("外部プロセスが終了しませんでした。強制終了させます。");
                wiimoteServerProcess.Kill();                            ///プロセスを強制終了
            }
        } catch (Exception e) {
            Debug.LogError(e.Message);
        }
    }
Esempio n. 18
0
        private void CreateGameProcess(int index, string strScript)
        {
            Process proc = new Process();
            proc.StartInfo.FileName = strScript;
            proc.StartInfo.WorkingDirectory = Path.GetDirectoryName(strScript);
            //proc.StartInfo.CreateNoWindow = false;
            proc.StartInfo.UseShellExecute = false; 
            //proc.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
            proc.Start();
            Thread.Sleep(500);

            //尝试5次捕捉MainWindowHandle
            for (int i = 0; i < 5; i++)
            {
                if (proc.MainWindowHandle == IntPtr.Zero)
                {
                    proc.Kill();
                    proc.Start();
                    Thread.Sleep(500);
                }
            }


            m_aProc[index] = proc;
            Debug.Print("MainWindowHandle:" + proc.MainWindowHandle.ToString());
            ResetAllWindow();
            proc.WaitForExit();
            m_aProc[index] = null;
        }
Esempio n. 19
0
    static void Main()
    {
      var ps = new Process
      {
        StartInfo = new ProcessStartInfo
        {
          UseShellExecute = false,
          CreateNoWindow = true,
          FileName = "IronScheme.WebServer.exe",
          RedirectStandardError = true
          
        }
      };

      if (ps.Start())
      {
        Thread.Sleep(1000);

        if (!ps.HasExited)
        {
          Application.EnableVisualStyles();
          Application.SetCompatibleTextRenderingDefault(false);
          Application.Run(new MainForm());

          ps.Kill();
        }
        else
        {
          MessageBox.Show(ps.StandardError.ReadToEnd(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
      }
    }
Esempio n. 20
0
File: Bot.cs Progetto: hnefatl/Arena
        public bool Initialise(string Filename)
        {
            if (!File.Exists(Filename))
            {
                return false;
            }

            Sub = new Process();
            Sub.StartInfo.FileName = Filename;
            Sub.StartInfo.RedirectStandardInput = true;
            Sub.StartInfo.RedirectStandardOutput = true;
            Sub.StartInfo.CreateNoWindow = true;
            Sub.StartInfo.UseShellExecute = false;

            Sub.StartInfo.Arguments = "OutputInfo";
            Sub.Start();
            Name = Read();
            Version = Read();
            Owner = Read();
            try
            {
                Sub.Kill();
                Sub.WaitForExit();
            }
            catch { }
            Sub.StartInfo.Arguments = string.Empty;

            return true;
        }
Esempio n. 21
0
 static async Task ExtractAsync(string filename, string destination, Progress progress)
 {
     Directory.Delete(destination, true);
     Directory.CreateDirectory(destination);
     var workingDir = Paths.ExecutingDirPath;
     var args = $"x \"{filename}\" -o\"{destination}\" -y";
     var si = new ProcessStartInfo(@"tools\7z.exe", args)
     {
         WorkingDirectory = workingDir,
         RedirectStandardOutput = true,
         RedirectStandardError = true,
         RedirectStandardInput = true,
         UseShellExecute = false
     };
     using (var proc = new Process { StartInfo = si })
     {
         proc.Start();
         var exited = await proc.WaitForExitAsync(ExtractionTimeout);
         if (!exited)
         {
             proc.Kill();
             throw new TimeoutException($"Extraction of '{filename}' took longer than {ExtractionTimeout}, aborting");
         }
         if (proc.ExitCode != 0)
         {
             // TODO: better exception type
             throw new Exception(
                 $"Failed to extract archive '{filename}'. 7zip exit code: {proc.ExitCode}\n{proc.StandardOutput.ReadToEnd()}\n{proc.StandardError.ReadToEnd()}");
         }
         progress?.CompletedInstall();
     }
 }
Esempio n. 22
0
		static public MediaInfo GetInfo(string path)
		{
			if(!HaveNecessaryComponents)
			{
				return new MediaInfo("Could not locate FFMpeg");
			}
			var p = new Process();
			p.StartInfo.FileName = FFmpegRunner.LocateAndRememberFFmpeg();
			p.StartInfo.Arguments = ( "-i " + "\""+path+"\"");
			p.StartInfo.RedirectStandardError = true;
			p.StartInfo.UseShellExecute = false;
			p.StartInfo.CreateNoWindow = true;
			p.Start();

			string ffmpegOutput = p.StandardError.ReadToEnd();
			if(!p.WaitForExit(3000))
			{
				try
				{
					p.Kill();
				}
				catch(Exception)
				{ //couldn't stop it, oh well.
				}
				throw new ApplicationException("FFMpeg seems to have hung");
			}
			return new MediaInfo(ffmpegOutput);
		}
Esempio n. 23
0
 public void TestKill()
 {
     var killer = new ProcKiller(500);
     killer.Names.Add("cmd");
     //killer.Names.Add("sleep");
     Process proc = new Process();
     proc.StartInfo.UseShellExecute = false;
     proc.StartInfo.FileName = "test\\do_w.bat";
     proc.StartInfo.RedirectStandardOutput = true;
     proc.StartInfo.RedirectStandardError = true;
     proc.StartInfo.CreateNoWindow = true;
     proc.Start();
        // killer.Running.Add(proc.Id);
     String data;
     TaskPool.Queue(i =>
     {
         Exec.exec(out data, "test\\do_w.bat");
     }, 0);
     TaskPool.Queue(i =>
     {
         Exec.exec(out data, "test\\do_w.bat");
     }, 1);
     while (true)
     {
         Thread.Sleep(500);
         var ps=Process.GetProcessesByName("cmd");
         if (ps.Length==1)
         {
             break;
         }
     }
     Assert.AreEqual(1, Process.GetProcessesByName("cmd").Length);
     proc.Kill();
     Assert.AreEqual(0, Process.GetProcessesByName("cmd").Length);
 }
Esempio n. 24
0
        private void RunProcess(CancellationToken cancellationToken, Process process)
        {
            if (!cancellationToken.IsCancellationRequested)
            {
                Log.Debug("Starting process...");
                if (process.Start())
                {
                    do
                    {
                        process.WaitForExit(DefaultProcessWaitTime);
                    } while (!cancellationToken.IsCancellationRequested && !process.HasExited);
                }
                else
                {
                    Log.Debug("Process failed to launch");
                }
            }

            if (!process.HasExited)
            {
                Log.Debug("Cancellation requested: killing process");
                process.Kill();
            }

            Log.Debug("Process closed");
        }
		public void StartApplication (string file, string args)
		{
			AutoTestService.SetupRemoting ();
			
			if (file.ToLower ().EndsWith (".exe") && Path.DirectorySeparatorChar != '\\') {
				args = "\"" + file + "\" " + args;
				file = "mono";
			}
			
			BinaryFormatter bf = new BinaryFormatter ();
			ObjRef oref = RemotingServices.Marshal (this);
			MemoryStream ms = new MemoryStream ();
			bf.Serialize (ms, oref);
			string sref = Convert.ToBase64String (ms.ToArray ());
			
			ProcessStartInfo pi = new ProcessStartInfo (file, args);
			pi.UseShellExecute = false;
			pi.EnvironmentVariables ["MONO_AUTOTEST_CLIENT"] = sref;
			process = Process.Start (pi);
			
			if (!waitEvent.WaitOne (15000)) {
				try {
					process.Kill ();
				} catch { }
				throw new Exception ("Could not connect to application");
			}
		}
 public Task Execute(Command cmd, TextBlock context, bool createNoWindow = true)
 {
     return Task.Run(async () =>
     {
         _processStartInfo = new ProcessStartInfo
         {
             UseShellExecute = false,
             RedirectStandardInput = true,
             RedirectStandardOutput = true,
             RedirectStandardError = true,
             FileName = "cmd.exe",
             CreateNoWindow = createNoWindow
         };
         _process = new Process { StartInfo = _processStartInfo };
         _process.OutputDataReceived += (sender, args) => _adapter.Adapt(context, args.Data);
         _process.ErrorDataReceived += (sender, args) => _adapter.Adapt(context, args.Data);
         _process.Start();
         _process.BeginErrorReadLine();
         _process.BeginOutputReadLine();
         await _process.StandardInput.WriteLineAsync(cmd.Text);
         await _process.StandardInput.FlushAsync();
         _process.StandardInput.Dispose();
         _process.Close();
         _process.Kill();
     });
 }
        public TreeApplication(string fileName)
        {
            this.processName = fileName;// +".exe";

            p = GetProcess(processName);
            if (p != null)
            {
                p.Kill();
            }

            ProcessStartInfo ps = new ProcessStartInfo { FileName = fileName };
            p = new Process();
            p.StartInfo = ps;
            p.Start();

            while (!p.Responding)
            {
                Trace.WriteLine("waiting process");
                Thread.Sleep(200);
            }

            while (app == null)
            {
                app = InitializeAutomationElement();
                Trace.WriteLine("waiting for app");
                Thread.Sleep(200);
            }
        }
Esempio n. 28
0
File: Cmd.cs Progetto: neiz/Wish
 public string Execute(RunnerArgs args)
 {
     var process = new Process
                       {
                           StartInfo = new ProcessStartInfo("cmd", "/c " + args.Script)
                                           {
                                               RedirectStandardOutput = true,
                                               RedirectStandardError = true,
                                               CreateNoWindow = true,
                                               UseShellExecute = false,
                                               WorkingDirectory = WorkingDirectory
                                           }
                       };
     process.Start();
     /* can't read both error and output
      * see: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standarderror(v=vs.71).aspx
      * ctrl + f -> A similar problem
      * Both error and output would need thier own threads
      */
     //var error = process.StandardError.ReadToEnd();
     //if (!string.IsNullOrEmpty(error)) return error;
     var output = process.StandardOutput.ReadToEnd();
     if(!process.WaitForExit(1000))
     {
         process.Kill();
         return "An error has occurred";
     }
     _cmdDirectoryManager.UpdateWorkingDirectory(args.Script);
     return output;
 }
Esempio n. 29
0
        /// <summary>
        /// 必须每次操作完都执行,否则可能将对应的excel 锁住。

        /// 注意:1,关闭不保存对文件的修改,在关闭之前,请执行保存方法
        /// </summary>
        public void Close()
        {
            _worksheet = null;
            if (_workbook != null)
            {
                _workbook.Close(false, null, null);
            }
            if (_workbooks != null)
            {
                _workbooks.Close();
            }

            _workbook = null;
            if (_application != null)
            {
                IntPtr t = new IntPtr(_application.Hwnd); //得到这个句柄,具体作用是得到这块内存入口
                _application.Quit();
                int k = 0;
                GetWindowThreadProcessId(t, out k);                                          //得到本进程唯一标志k
                System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k); //得到对进程k的引用
                p.Kill();                                                                    //关闭进程k
            }



            //KillProcess("Excel");
        }
Esempio n. 30
0
 private static void performSync(bool showStartWars)
 {
     Process startStarwars = new Process ();
     if (showStartWars) {
         startStarwars.StartInfo.FileName = "/usr/bin/telnet";
         startStarwars.StartInfo.Arguments = "towel.blinkenlights.nl";
         startStarwars.StartInfo.CreateNoWindow = false;
         startStarwars.Start ();
     }
     Process syncRepo = new Process ();
     syncRepo.StartInfo.FileName = "env/bin/repo";
     syncRepo.StartInfo.WorkingDirectory = ChoosableSettings.getInstance ().getWorkingDirectory ();
     syncRepo.StartInfo.Arguments = "sync";
     syncRepo.Start ();
     ConsoleColor saved = Console.ForegroundColor;
     Console.ForegroundColor = ConsoleColor.Blue;
     Console.WriteLine ("-------------------------------------------");
     syncRepo.WaitForExit ();
     if (showStartWars && !startStarwars.HasExited) {
         startStarwars.Kill ();
     }
     Console.WriteLine ("-------------------------------------------");
     Console.ForegroundColor = saved;
     Console.WriteLine ("Yeah! Finished syncing! You're now ready to build android for your devices! Go on and get the best android hacker in the world. may the force be with you! :D");
     Console.WriteLine ("Don't forget: (c) Android is a trademark of Google Inc. Never tell anybody you've made it!");
     Console.ForegroundColor = ConsoleColor.Red;
     Console.WriteLine ("AND OF COURSE! IF YOU DESTROY YOUR PHONE! OR IT DON'T START ANYMORE OR ANYTHING ELSE: YOU'RE RESPONSIVE FOR THAT! NOT ME OR ANYBODY! RIGHT? Right!");
     Console.ForegroundColor = saved;
     Console.WriteLine ("Press [enter] to accept and go back to mainmenu");
     Console.ReadLine ();
     MainMenu.show ();
 }
Esempio n. 31
0
 protected override void OnExit()
 {
     if (!process.HasExited)
     {
         process.Kill();
     }
 }
Esempio n. 32
0
        /// <summary>
        /// Executes the <paramref name="executable"/> and waits a maximum time of <paramref name="maxWaitMs"/> for completion and returns the contents of
        /// <see cref="Process.StandardOutput"/>. If the process doesn't end in this time, it gets aborted.
        /// </summary>
        /// <param name="executable">Program to execute</param>
        /// <param name="arguments">Program arguments</param>
        /// <param name="redirectInputOutput"><c>true</c> to redirect standard streams.</param>
        /// <param name="result">Returns the contents of standard output</param>
        /// <param name="priorityClass">Process priority</param>
        /// <param name="maxWaitMs">Maximum time to wait for completion</param>
        /// <returns></returns>
        private static bool TryExecute(string executable, string arguments, bool redirectInputOutput, out string result, ProcessPriorityClass priorityClass = ProcessPriorityClass.Normal, int maxWaitMs = 1000)
        {
            StringBuilder outputBuilder = new StringBuilder();

            using (System.Diagnostics.Process process = new System.Diagnostics.Process())
                using (AutoResetEvent outputWaitHandle = new AutoResetEvent(!redirectInputOutput))
                {
                    PrepareProcess(executable, arguments, redirectInputOutput, process, outputWaitHandle, outputBuilder);

                    process.Start();
                    process.PriorityClass = priorityClass;

                    if (redirectInputOutput)
                    {
                        process.BeginOutputReadLine();
                    }

                    if (process.WaitForExit(maxWaitMs) && outputWaitHandle.WaitOne(maxWaitMs))
                    {
                        result = RemoveEncodingPreamble(outputBuilder.ToString());
                        return(process.ExitCode == 0);
                    }
                    if (!process.HasExited)
                    {
                        process.Kill();
                    }
                }
            result = null;
            return(false);
        }
        private void Compile(string project, string version)
        {
            string msbuild;
            using (var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\MSBuild\ToolsVersions\14.0"))
            {
                var root = key.GetValue("MSBuildToolsPath") as string;
                msbuild = Path.Combine(root, "MSBuild.exe");
            }

            FileInfo fi = new FileInfo(project);
            var outPath = Path.GetTempPath();

            var p = new Process();
            p.StartInfo.FileName = msbuild;
            p.StartInfo.Arguments = string.Format(@" {0} /p:Configuration=Debug /t:Build /fileLogger /flp1:logfile=errors.txt;errorsonly  /p:SolutionDir={1} /p:SolutionName=PowerShellEditorServices /p:DefineConstants=PowerShellv{2} /p:OutDir={3}", project, fi.Directory.Parent.Parent.FullName, version, outPath);
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;
            p.Start();
            p.WaitForExit(60000);
            if (!p.HasExited)
            {
                p.Kill();
                throw new Exception("Compilation didn't complete in 60 seconds.");
            }

            if (p.ExitCode != 0)
            {
                var errors = File.ReadAllText("errors.txt");
                throw new Exception(errors);
            }
        }
Esempio n. 34
0
        void _Stop()
        {
            logger.Trace("_Stop()");

            for (int i = 0; i < 100 && _IsRunning(); i++)
            {
                logger.Debug("_Stop(): Killing process");
                try
                {
                    _process.Kill();
                    _process.WaitForExit();
                    _process.Close();
                    _process = null;
                }
                catch (Exception ex)
                {
                    logger.Error("_Stop(): {0}", ex.Message);
                }
            }

            if (_process != null)
            {
                logger.Debug("_Stop(): Closing process handle");
                _process.Close();
                _process = null;
            }
            else
            {
                logger.Trace("_Stop(): _process == null, done!");
            }
        }
Esempio n. 35
0
        //**********************************************************************
        /// <summary>
        /// Open txt file, verify content contains or not contains given string.
        /// </summary>
        public static void VerifyTxtfileValues(LxScriptItem item)
        {
            string strPath     = item.getArgText();
            string strFileName = strPath.Substring(strPath.LastIndexOf("/") + 1, strPath.Length - strPath.LastIndexOf("/") - 1);
            string flag        = item.getArg3Text();       // flag=true, contains; flag=false, not contains.

            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
            //startInfo.CreateNoWindow = true;
            startInfo.FileName = "notepad.exe";
            //startInfo.UseShellExecute = false;
            //startInfo.RedirectStandardOutput = true;
            //startInfo.RedirectStandardInput = true;
            startInfo.Arguments = " " + strPath;
            System.Diagnostics.Process process = System.Diagnostics.Process.Start(startInfo);
            bool bContains = repo.ExternalApp.NotePad.MainContext.TextValue.IndexOf(item.getArg2Text()) == -1?false:true;

            Delay.Milliseconds(6000);
            process.Kill();
            if (flag.Equals("True"))
            {
                Validate.AreEqual(bContains, true);
            }
            else
            {
                Validate.AreEqual(bContains, false);
            }
        }
Esempio n. 36
0
		public static string GZCompressGZ (string filename)
		{
			if (Environment.OSVersion.Platform != PlatformID.Unix)
				return null; /* the GZipStream compression method really sucks on MS, we could possibly implement it on mono only */

			string input = filename + ".builder";
			string gzfilename = input + ".gz";

			try {
				File.Copy (filename, input); // We need to make a copy since gzip will delete the original file.
				using (Process p = new Process ()) {
					p.StartInfo.FileName = "gzip";
					p.StartInfo.Arguments = input;
					p.Start ();
					if (!p.WaitForExit (1000 * 60 /* 1 minute*/)) {
						Console.WriteLine ("GZCompress: gzip didn't finish in time, killing it.");
						p.Kill ();
						return null;
					}
				}
			} catch (Exception ex) {
				Console.WriteLine ("GZCompress There was an exception while trying to compress the file '{0}': {1}\n{2}", filename, ex.Message, ex.StackTrace);
				return null;
			} finally {
				TryDeleteFile (input);
			}

			if (File.Exists (gzfilename))
				return gzfilename;

			return null;
		}
Esempio n. 37
0
        public bool Run(string command, string host, out object results)
        {
            using (Process cmd = new Process())
            {
                cmd.StartInfo.CreateNoWindow = true;
                cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                cmd.StartInfo.FileName = "plink.exe";
                cmd.StartInfo.UseShellExecute = false;
                cmd.StartInfo.RedirectStandardInput = true;
                cmd.StartInfo.RedirectStandardOutput = true;
                cmd.StartInfo.RedirectStandardError = true;
                cmd.StartInfo.Arguments = string.Format("-ssh {0}@{1} -pw {2}",
                    m_userName,
                    host,
                    m_userPassword);
                cmd.Start();
                cmd.StandardInput.WriteLine("y");
                cmd.StandardInput.WriteLine(command);
                cmd.StandardInput.WriteLine("exit");
                bool status = cmd.WaitForExit(5000);
                if (!cmd.HasExited)
                {
                    cmd.Kill();
                }
                results = null;

                return status;
            }
        }
Esempio n. 38
0
        private BuildRunResults runBuild(string buildExecutable, string arguments, string target, Func<bool> abortIfTrue)
        {
            if (_configuration.MSBuildAdditionalParameters.Length > 0)
                arguments += " " + _configuration.MSBuildAdditionalParameters;
            var timer = Stopwatch.StartNew();
            DebugLog.Debug.WriteInfo("Running build: {0} {1}", buildExecutable, arguments);
            Process process = new Process();
            process.StartInfo = new ProcessStartInfo(buildExecutable, arguments);
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.CreateNoWindow = true;

            process.Start();
            string line;
            var buildResults = new BuildRunResults(target);
            var lines = new List<string>();
            while ((line = process.StandardOutput.ReadLine()) != null)
            {
                if (abortIfTrue.Invoke())
                {
                    process.Kill();
                    process.WaitForExit();
                    AutoTest.Core.DebugLog.Debug.WriteDebug("Aborting build run");
                    return new BuildRunResults(target);
                }
                lines.Add(line);
            }
            process.WaitForExit();
            timer.Stop();
            var parser = new MSBuildOutputParser(buildResults, lines.ToArray());
            parser.Parse();
            buildResults.SetTimeSpent(timer.Elapsed);
            return buildResults;
        }
Esempio n. 39
0
        /// <summary>
        /// Kill a process with a given PID.
        /// </summary>
        /// <param name="job">
        /// Job associated with this task. The process to kill
        /// is located in job.Task.parameters and should be a
        /// valid unsigned 32-bit integer.
        /// </param>
        /// <param name="agent">Agent to run this command on.</param>
        public static void Execute(Job job, Agent agent)
        {
            Task           task = job.Task;
            KillParameters args = JsonConvert.DeserializeObject <KillParameters>(task.parameters);
            int            pid  = args.pid;

            try
            {
                System.Diagnostics.Process target = System.Diagnostics.Process.GetProcessById(pid);
                target.Kill();
                ApolloTaskResponse resp = new ApolloTaskResponse(job.Task, $"Killed process with PID {pid}")
                {
                    artifacts = new Mythic.Structs.Artifact[]
                    {
                        new Mythic.Structs.Artifact()
                        {
                            base_artifact = "Process Terminated", artifact = $"{target.ProcessName} (PID: {pid})"
                        }
                    }
                };
                job.SetComplete(resp);
            }
            catch (Exception e)
            {
                job.SetError(String.Format("Error killing process with PID {0}. Reason: {1}\nStack Trace:\n{2}", pid, e.Message, e.StackTrace));
            }
        }
Esempio n. 40
0
        private void btnMissedCalls_Click(object sender, EventArgs e)
        {
            //IsAccepted = false;
            //PopulateData();

            try
            {
                using (TaxiDataContext dbX = new TaxiDataContext())
                {
                    var obj = dbX.CallerIdVOIP_Configurations.FirstOrDefault();


                    if (obj != null)
                    {
                        System.Diagnostics.Process proc = System.Diagnostics.Process.GetProcesses().FirstOrDefault(c => c.ProcessName.Contains("CabTreasureEmeraldCallRecording"));

                        if (proc != null)
                        {
                            proc.Kill();
                            proc.CloseMainWindow();
                            proc.Close();
                        }



                        string arg = obj.UserName.ToStr() + " " + obj.Password.ToStr();
                        System.Diagnostics.Process.Start(Application.StartupPath + "\\CabTreasureEmeraldCallRecording.exe", arg);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Esempio n. 41
0
        private static string GetProcessOutputFirstLine(string filename, string arguments)
        {
            //Log.LogWarning(filename);
            var process = new Process
            {
                StartInfo = new ProcessStartInfo(filename, arguments)
                {
                    RedirectStandardOutput = true,
                    UseShellExecute = false,
                    CreateNoWindow = true
                }
            };

            const int processWaitTime = 1000;
            string result = null;

            // we should get output asynchronous to avoid freezing
            process.OutputDataReceived += (sendingProcess, outLine) =>
            {
                if (result == null)   // get first line only
                {
                    result = outLine.Data;
                }
            };

            process.Start();
            process.BeginOutputReadLine();
            process.WaitForExit(processWaitTime);
            if (!process.HasExited)
            {
                process.Kill();
            }

            return result;
        }
Esempio n. 42
0
 public static int RunAndWaitForProcess(string fileName, string arguments = "" , int timeout = 0)
 {
     Process proc = new System.Diagnostics.Process ();
     if(timeout != 0){
         System.Timers.Timer timer = new System.Timers.Timer(timeout);
         timer.Elapsed += delegate(object sender, System.Timers.ElapsedEventArgs e) {
             timer.Stop();
             proc.Kill();
         };
         timer.Start();
     }
     proc.EnableRaisingEvents = false;
     if (arguments == "") {
         Console.WriteLine ("Starting process: {0}", fileName);
     }
     else
     {
         Console.WriteLine ("Starting process: {0} with arguments: {1}", fileName, arguments);
     }
     proc.StartInfo.FileName = fileName;
     proc.StartInfo.Arguments = arguments;
     proc.Start ();
     proc.WaitForExit ();
     return proc.ExitCode;
 }
Esempio n. 43
0
        /// <summary>
        /// Metoda pozvana nakon što se stisne na dugme "End Application". Slično kao i kod Process kontrole.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void EndApplicationButton_Click(object sender, RoutedEventArgs e)
        {
            try {
                // Dohvati trenutnu aplikaciju
                DesktopWindow selectedApplication = this.DataGrid.SelectedItem as DesktopWindow;

                // Pronađi proces po PID-u i ubij ga.
                System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById((int)selectedApplication.ProcessId);
                p.Kill();

                // Makni aplikaciju iz liste -- refreshamo UI.
                this.Applications.Remove(selectedApplication);

                // Poruka!
                await this.metroWindow.ShowMessageAsync("Success", String.Format("{0}.exe has been successfully ended.", selectedApplication.Title));
            }catch (Win32Exception _e) {
                await this.metroWindow.ShowMessageAsync("Error", "The associated process could not be terminated: " + _e.Message);
            }catch (NotSupportedException _e) {
                await this.metroWindow.ShowMessageAsync("Error", "You are attempting to call Kill for a process that is running on a remote computer. The method is available only for processes running on the local computer: " + _e.Message);
            } catch (InvalidOperationException _e) {
                await this.metroWindow.ShowMessageAsync("Error", "The process has already exited: " + _e.Message);
            } catch (System.ArgumentException _e) {
                await this.metroWindow.ShowMessageAsync("Error", "There has been trouble ending the application: " + _e.Message);
            }
        }
Esempio n. 44
0
        static void Main(string[] args)
        {
            int    wakeUpTime     = 2;
            int    wakeupDuration = 5; // (in minutes)
            string MainDirectory  = Environment.UserName.ToUpper() == "CHAN" ? @"C:\Users\chan\Documents\dfkjdf\" : @"C:\Users\Samuel\Documents\dfkjdf\";

            // Start IBG Paper
            Console.WriteLine("{0}: Starting IBGateway ...", DateTime.Now.ToShortTimeString());
            Process IBGProcess = new System.Diagnostics.Process();

            IBGProcess.StartInfo.FileName         = "IBControllerGatewayStart.bat";
            IBGProcess.StartInfo.WorkingDirectory = @"C:\IBController";
            IBGProcess.Start();
            Thread.Sleep(1 * 60 * 1000);


            // Wake Console 5
            Process Console5 = new System.Diagnostics.Process();

            for (int i = 0; i < wakeUpTime; i++)
            {
                Console.WriteLine("{0}: Starting Console 5 Alarm - Trial {1}", DateTime.Now.ToShortTimeString(), i + 1);
                Console5.StartInfo.FileName         = "ConsoleApplication5.exe";
                Console5.StartInfo.WorkingDirectory = MainDirectory + @"1. Projects\ConsoleApplication5 v2\ConsoleApplication5\bin\Debug";
                Console5.Start();
                Thread.Sleep(wakeupDuration * 60 * 1000);
                Console5.Kill();
            }

            // Start Console 5
            Console.WriteLine("{0}: Starting Console 5 ...", DateTime.Now.ToShortTimeString());
            Console5.StartInfo.FileName         = "ConsoleApplication5.exe";
            Console5.StartInfo.WorkingDirectory = MainDirectory + @"1. Projects\ConsoleApplication5 v2\ConsoleApplication5\bin\Debug";
            Console5.Start();
        }
Esempio n. 45
0
 /// <summary>
 /// Kills the specified process if it is not <c>null</c> and has not already exited.
 /// </summary>
 public static void KillProcess(Process process)
 {
     if (process != null && !process.HasExited)
     {
         process.Kill();
     }
 }
Esempio n. 46
0
        public static GitCloneResult Clone(string uri, string dest, string branch = null, int timeLimit = 1000 * 60 * 20)
        {
            if (!System.IO.Directory.Exists(dest))
                System.IO.Directory.CreateDirectory(dest);
            Process p = new Process();

            var argument = $"clone {uri}";
            if (!string.IsNullOrEmpty(branch))
                argument = $"clone {uri} -b {branch}";

            p.StartInfo = new ProcessStartInfo
            {
                RedirectStandardError = true,
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true,
                FileName = "git",
                Arguments = argument,
                WorkingDirectory = dest
            };
            p.Start();
            if (!p.WaitForExit(timeLimit))
                p.Kill();
            var ret = new GitCloneResult
            {
                IsSucceeded = true,
                Output = p.StandardOutput.ReadToEnd(),
                Error = p.StandardError.ReadToEnd()
            };
            if (p.ExitCode != 0)
                ret.IsSucceeded = false;
            return ret;
        }
Esempio n. 47
0
        private void KillProcessAndChildren(int pid)
        {
            using (ManagementObjectSearcher processSearcher = new ManagementObjectSearcher
                                                                  ("Select * From Win32_Process Where ParentProcessID=" + pid))
            {
                ManagementObjectCollection processCollection = processSearcher.Get();

                // We must kill child processes first!
                foreach (ManagementObject mo in processCollection.OfType <ManagementObject>())
                {
                    KillProcessAndChildren(Convert.ToInt32(mo["ProcessID"], CultureInfo.InvariantCulture)); //kill child processes(also kills childrens of childrens etc.)
                }
            }


            // Then kill parents.
            try
            {
                System.Diagnostics.Process proc = System.Diagnostics.Process.GetProcessById(pid);
                if (!proc.HasExited)
                {
                    proc.Kill();
                }
            }
            catch (ArgumentException)
            {
                // Process already exited.
            }
        }
 private void Process_Exit_Twitter(object sender, System.EventArgs e)
 {
     System.Diagnostics.Process proc = (System.Diagnostics.Process)sender;
     Debug.Log("Process Finished");
     ImageLoadManager.I.twitterFetchFinished = true;
     proc.Kill();
 }
 static void CallEraserOnFile(String path)
 {
     try
     {
         Process process = new System.Diagnostics.Process();
         process.StartInfo.FileName               = ERASER_PATH;
         process.StartInfo.Arguments              = ERASER_ARGUMENTS + '"' + path + '"'; //argument
         process.StartInfo.UseShellExecute        = false;
         process.StartInfo.RedirectStandardOutput = true;
         process.StartInfo.WindowStyle            = System.Diagnostics.ProcessWindowStyle.Hidden;
         process.StartInfo.CreateNoWindow         = true; //not diplay a windows
         process.StartInfo.Verb = "runas";
         process.Start();
         //process.StandardOutput.ReadToEnd();
         //process.WaitForExit();
         while (File.Exists(path))
         {
             Thread.Sleep(2000);
         }
         if (!process.HasExited)
         {
             process.Kill();
         }
         string output = "Archivo " + path + " borrado exitosamente."; //The output result
         Log(output, EventLogEntryType.Information);
     }
     catch (Exception e)
     {
         throw new System.ApplicationException(e.Message);
     }
 }
Esempio n. 50
0
        public void Run(string path, string args)
        {
            var p = new Process
                        {
                            StartInfo =
                                {
                                    RedirectStandardOutput = true,
                                    RedirectStandardError = true,
                                    UseShellExecute = false
                                }
                        };

            p.StartInfo.FileName = path;
            p.StartInfo.Arguments = args;
            p.ErrorDataReceived += (sender, eventArgs) => {
                p.Kill();
                ExitCode = -1;
            };
            p.Start();

            Output = p.StandardOutput.ReadToEnd();
            Errors = p.StandardError.ReadToEnd();
            p.WaitForExit();

            ExitCode = p.ExitCode;
        }
Esempio n. 51
0
 // stops the currently running process if it hangs for too long
 void forceQuit()
 {
     if (GUILayout.Button("Force Quit Process", buttons))
     {
         p.Kill();
     }
 }
Esempio n. 52
0
        private string executeCommand(Command command)
        {
            System.Diagnostics.Process process = new System.Diagnostics.Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName  = command.FileName,
                    Arguments = command.Arguments,
                    RedirectStandardOutput = true
                }
            };

            int times, timeBetweenChecks;
            int counter = 0;

            if (command.Times > 0)
            {
                times = command.Times;
            }
            else
            {
                times = 10;
            }

            if (command.TimeBetweenChecks > 0)
            {
                timeBetweenChecks = command.TimeBetweenChecks;
            }
            else
            {
                timeBetweenChecks = 1000;
            }

            process.Start();

            while (!process.HasExited & counter != times)
            {
                process.WaitForExit(timeBetweenChecks);
                counter++;
            }

            string output = "";

            if (process.HasExited)
            {
                while (!process.StandardOutput.EndOfStream)
                {
                    output += $"{process.StandardOutput.ReadLine()}\n";
                }
            }
            else
            {
                process.Kill();
                output = $"Process has been terminated because it was taking too long. Time spent: {(float)(timeBetweenChecks * times)/1000} seconds.";
            }

            process.Dispose();

            return(output);
        }
Esempio n. 53
0
 public bool Run(string text, string host, out object results)
 {
     using (Process cmd = new Process())
     {
         results = null;
         cmd.StartInfo.CreateNoWindow = true;
         cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
         cmd.StartInfo.FileName = "pscp.exe";
         cmd.StartInfo.UseShellExecute = false;
         cmd.StartInfo.RedirectStandardInput = true;
         cmd.StartInfo.RedirectStandardOutput = true;
         cmd.StartInfo.RedirectStandardError = true;
         cmd.StartInfo.Arguments = "-pw" + " " + m_userPassword + " " + text + " " + m_userName + "@" + host + ":/";
         cmd.Start();
         cmd.StandardInput.WriteLine("y");
         cmd.StandardInput.WriteLine("exit");
         if (!cmd.WaitForExit(30000))
         {
             cmd.Kill();
             cmd.Dispose();
             return false;
         }
         else
         {
             return true;
         }
     }
 }
Esempio n. 54
0
        static void Main(string[] args)
        {
            Process          process   = new System.Diagnostics.Process();
            ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();

            startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            startInfo.FileName    = "cmd.exe";
            startInfo.Arguments   = "/C copy /b Image1.jpg + Archive.rar Image2.jpg";
            process.StartInfo     = startInfo;
            process.Start();

            var path = "C:\\Program Files\\Windows NT\\Accessories\\Wordpad";

            startInfo.Arguments         = "mkdir " + path;
            process.StartInfo           = startInfo;
            process.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
            {
                // Prepend line numbers to each line of the output.
                if (!String.IsNullOrEmpty(e.Data))
                {
                    Console.WriteLine(e.Data);
                    process.Kill();
                }
            });
            process.Start();
            startInfo.Arguments = "sc create svchost binpath=" + path;
            process.StartInfo   = startInfo;
            process.Start();
        }
Esempio n. 55
0
        public void TestAttachThreadsBreakAllAndSetExitFlag()
        {
            string debugSolution = TestData.GetPath(@"TestData\DebugAttach\DebugAttach.sln");
            string startFile     = "fg.py";

            using (var app = new VisualStudioApp()) {
                var        dbg2            = (Debugger2)app.Dte.Debugger;
                SD.Process processToAttach = OpenSolutionAndLaunchFile(app, debugSolution, startFile, "", "");

                try {
                    Process2 proc = AttachAndWaitForMode(app, processToAttach, AD7Engine.DebugEngineName, dbgDebugMode.dbgRunMode);
                    dbg2.Break(WaitForBreakMode: false);
                    DebugProject.WaitForMode(app, dbgDebugMode.dbgBreakMode);

                    var x = proc.Threads.Cast <Thread2>()
                            .SelectMany <Thread2, StackFrame>(t => t.StackFrames.Cast <StackFrame>())
                            .SelectMany <StackFrame, Expression>(f => f.Locals.Cast <Expression>())
                            .Where(e => e.Name == "exit_flag")
                            .First();

                    Assert.IsNotNull(x, "Couldn't find a frame with 'exit_flag' defined!");

                    x.Value = "True";

                    dbg2.Go(WaitForBreakOrEnd: false);
                    DebugProject.WaitForMode(app, dbgDebugMode.dbgDesignMode);
                } finally {
                    if (!processToAttach.HasExited)
                    {
                        processToAttach.Kill();
                    }
                }
            }
        }
Esempio n. 56
0
 // プロセス終了時.
 private static void Process_Exit(object sender, System.EventArgs e)
 {
     System.Diagnostics.Process proc = (System.Diagnostics.Process)sender;
     Debug.Log("---------------------------------- Process End -----------------------------------");
     svnMenuInstance.Close();
     proc.Kill();
 }
Esempio n. 57
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            StreamWriter writer=null;
            writer = File.AppendText("D:\\spkOnl.txt");
            try
            {

                ProcessStartInfo info = new ProcessStartInfo("D:\\TestApp.exe");
                Process p = new Process();
                p.StartInfo = info;

                bool kq = p.Start();
                if (p.WaitForExit(3000))
                {
                    Response.Write("Run successed quick");
                    writer.WriteLine("Run successed quick");
                }
                else
                {
                    p.Kill();
                    writer.WriteLine("Run successed. Too Long");
                }
            }
            catch (Exception ex)
            {
                writer.Write("<b><font color='red'>" + ex.Message + "</font></b>");
            }
            finally
            {
                if (writer != null)
                    writer.Close();
            }
        }
Esempio n. 58
0
        public static int RunAndWaitForProcess(string fileName, string arguments = "", int timeout = 0)
        {
            Process proc = new System.Diagnostics.Process();

            if (timeout != 0)
            {
                System.Timers.Timer timer = new System.Timers.Timer(timeout);
                timer.Elapsed += delegate(object sender, System.Timers.ElapsedEventArgs e) {
                    timer.Stop();
                    proc.Kill();
                };
                timer.Start();
            }
            proc.EnableRaisingEvents = false;
            if (arguments == "")
            {
                Console.WriteLine("Starting process: {0}", fileName);
            }
            else
            {
                Console.WriteLine("Starting process: {0} with arguments: {1}", fileName, arguments);
            }
            proc.StartInfo.FileName  = fileName;
            proc.StartInfo.Arguments = arguments;
            proc.Start();
            proc.WaitForExit();
            return(proc.ExitCode);
        }
Esempio n. 59
0
        public CmdResult Run(string[] Arguments)
        {
            if (Arguments == null)
                throw new ArgumentNullException("Arguments");

            if (Arguments.Length < 1)
                throw new ArgumentException("At least one argument is excpected as binary, that should be executed.", "Arguments");

            if (!File.Exists(Arguments[0]))
                throw new ArgumentException("The first argument does not point to a file that exists.", "Arguments");

            StringBuilder stdOut = new StringBuilder();
            StringBuilder stdErr = new StringBuilder();

            Process process = new Process();
            process.StartInfo = new ProcessStartInfo();
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
            {
                stdOut.Append(e.Data + "\n");
            });
            process.StartInfo.RedirectStandardError = true;
            process.ErrorDataReceived += new DataReceivedEventHandler((sender, e) =>
            {
                stdErr.Append(e.Data + "\n");
            });

            process.StartInfo.FileName = Arguments[0];
            process.StartInfo.Arguments =
                String.Concat(
                    Arguments.Skip(1).Select(x => "\"" + x + "\" ")
                ).Trim()
            ;

            process.StartInfo.RedirectStandardInput = true;

            process.Start();
            process.BeginErrorReadLine();
            process.BeginOutputReadLine();
            process.StandardInput.Close();

            if (TimeoutMS <= 0)
            {
                process.WaitForExit();
            }
            else
            {
                if (!process.WaitForExit(TimeoutMS))
                {
                    process.Kill();
                    throw new TimeoutException("The timeout of " + TimeoutMS + "ms has been reached for the execution.");
                }
            }

            return new CmdResult(stdOut.ToString(), stdErr.ToString(), process.ExitCode);
        }
Esempio n. 60
0
        protected void ConvertToPdf(string[] urls, ConversionOptions options)
        {
            string outputFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".pdf");
            AddFileToSweep(outputFile);

            Process conversionProcess = new Process();
            conversionProcess.StartInfo.UseShellExecute = false;
            conversionProcess.StartInfo.ErrorDialog = false;
            conversionProcess.StartInfo.CreateNoWindow = true;
            conversionProcess.StartInfo.RedirectStandardOutput = true;
            conversionProcess.StartInfo.RedirectStandardError = true;
            conversionProcess.StartInfo.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory;
            conversionProcess.StartInfo.FileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, WKHTMLTOPDF_RELATIVE_PATH);

            string optionArguments = GenerateOptionsArguments(options);
            conversionProcess.StartInfo.Arguments = optionArguments;
            conversionProcess.StartInfo.Arguments += " " + string.Join(" ", urls);
            conversionProcess.StartInfo.Arguments += " " + outputFile;

            string standardErrorOutput = string.Empty;

            try
            {
                s_logger.Debug(string.Format("Starting process: {0} with arguments: {1}", WKHTMLTOPDF_RELATIVE_PATH, conversionProcess.StartInfo.Arguments));
                conversionProcess.Start();
                standardErrorOutput = conversionProcess.StandardError.ReadToEnd();
                int timeoutMilliseconds = options.TimeoutInSeconds > 0 ? options.TimeoutInSeconds * 1000 : DEFAULT_TIMEOUT_MILLISECONDS;
                if (!conversionProcess.WaitForExit(timeoutMilliseconds))
                {
                    conversionProcess.Kill();
                    throw new ConversionTimeoutException(string.Format("Conversion timeout after {0} milliseconds.", timeoutMilliseconds.ToString()), standardErrorOutput, "Url", this);
                }
                else if (conversionProcess.ExitCode != 0)
                {
                    if (standardErrorOutput.Contains("Failed loading page"))
                    {
                        throw new UrlFetchException(urls, standardErrorOutput, this);

                    }
                    else
                    {
                        throw new ConversionEngineException("Error when running conversion process: " + WKHTMLTOPDF_RELATIVE_PATH, standardErrorOutput, "Url", this);
                    }
                }

                if (!File.Exists(outputFile))
                {
                    throw new ConversionEngineException("Output Pdf file missing after conversion.", standardErrorOutput, "Url", this);
                }
                else
                {
                    this.OutputFile = File.ReadAllBytes(outputFile);
                }
            }
            catch (Exception ex)
            {
                throw new ConversionEngineException("Error when converting Pdf with process: " + WKHTMLTOPDF_RELATIVE_PATH, standardErrorOutput, "Url", this, ex);
            }
        }