private bool CheckForNeedButton(ProcessPriorityClass priority)
 {
     if (priority == ProcessPriorityClass.Normal)
     {
         radioButton1.Checked = true;
         return true;
     }
     else if (priority == ProcessPriorityClass.AboveNormal)
     {
         radioButton2.Checked = true;
         return true;
     }
     else if (priority == ProcessPriorityClass.BelowNormal)
     {
         radioButton3.Checked = true;
         return true;
     }
     else if (priority == ProcessPriorityClass.High)
     {
         radioButton4.Checked = true;
         return true;
     }
     else if (priority == ProcessPriorityClass.Idle)
     {
         radioButton5.Checked = true;
         return true;
     }
     else if (priority == ProcessPriorityClass.RealTime)
     {
         radioButton6.Checked = true;
         return true;
     }
     return false;
 }
Beispiel #2
0
 public ConsoleProcess()
 {
     BufferSizeStdout = 4096;
     BufferSizeStderr = 4096;
     ModeStderr = CommunicationMode.Line;
     ModeStdout = CommunicationMode.Line;
     PriorityClass = ProcessPriorityClass.Normal;
 }
Beispiel #3
0
        public virtual void SetPriority(int processId, ProcessPriorityClass priority)
        {
            var process = Process.GetProcessById(processId);

            Logger.Info("Updating [{0}] process priority from {1} to {2}",
                        process.ProcessName,
                        process.PriorityClass,
                        priority);

            process.PriorityClass = priority;
        }
Beispiel #4
0
        public void Initialize()
        {
            this.CachedProcessPriorityClass = Process.GetCurrentProcess().PriorityClass;
            this.CachedThreadPriority = Thread.CurrentThread.Priority;
            
            Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
            Thread.CurrentThread.Priority = ThreadPriority.Highest;

            this.IsCachedStatus = true;

            this.Time(1, () => { });
        }
Beispiel #5
0
        private void ChangePriority(ProcessPriorityClass priority)
        {
            cbxPriority.SelectedValue = priority;

            for (var i = 0; i < tsmiPriority.DropDownItems.Count; i++)
            {
                var item = (ToolStripMenuItem)tsmiPriority.DropDownItems[i];
                item.Checked = (int)item.Tag == (int)priority;
            }

            processor.Priority = priority;
        }
#pragma warning disable 0618
		/// <summary>
		/// Initializes a new instance of the <see cref="HighPerformance"/> class.
		/// </summary>
		internal HighPerformance() {
			////if (!WaitForQuietCpu()) {
			////    Assert.Inconclusive("Timed out waiting for a quiet CPU in which to perform perf tests.");
			////}

			this.originalLoggerThreshold = LogManager.GetLoggerRepository().Threshold;
			LogManager.GetLoggerRepository().Threshold = LogManager.GetLoggerRepository().LevelMap["OFF"];
			this.powerSetting = new PowerManagment.PowerSetting(PowerManagment.PowerProfiles.HighPerformance);
			this.originalProcessPriority = Process.GetCurrentProcess().PriorityClass;
			Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
			Thread.CurrentThread.Priority = ThreadPriority.Highest;
			SpinCpu();
		}
 /// <summary>
 /// Initializes a new instance of the <see cref="ProcessInfo"/> class.
 /// </summary>
 /// <param name="filename">The filename.</param>
 /// <param name="arguments">The arguments.</param>
 /// <param name="workingDirectory">The working directory.</param>
 /// <param name="priority">The priority.</param>
 /// <param name="successExitCodes">The success exit codes.</param>
 public ProcessInfo(string filename, SecureArguments arguments, string workingDirectory, ProcessPriorityClass priority, int[] successExitCodes)
 {
     this.arguments = arguments;
     this.priority = priority;
     startInfo.FileName = filename.StripQuotes();
     startInfo.Arguments = arguments == null ? null : arguments.ToString(SecureDataMode.Private);
     startInfo.WorkingDirectory = workingDirectory.StripQuotes();
     startInfo.UseShellExecute = false;
     startInfo.CreateNoWindow = true;
     startInfo.RedirectStandardOutput = true;
     startInfo.RedirectStandardError = true;
     startInfo.RedirectStandardInput = false;
     this.successExitCodes = successExitCodes ?? new[] { 0 };
 }
Beispiel #8
0
 /// <summary>
 /// Executes the <paramref name="executable"/> and waits a maximum time of <paramref name="maxWaitMs"/> for completion. If the process doesn't end in 
 /// this time, it gets aborted. This method tries to impersonate the interactive user and run the process under its identity.
 /// </summary>
 /// <param name="executable">Program to execute</param>
 /// <param name="arguments">Program arguments</param>
 /// <param name="priorityClass">Process priority</param>
 /// <param name="maxWaitMs">Maximum time to wait for completion</param>
 /// <returns><c>true</c> if process was executed and finished correctly</returns>
 public static bool TryExecute_Impersonated(string executable, string arguments, ProcessPriorityClass priorityClass = ProcessPriorityClass.Normal, int maxWaitMs = INFINITE)
 {
   IntPtr userToken;
   if (!ImpersonationHelper.GetTokenByProcess(out userToken, true))
     return false;
   try
   {
     string unused;
     return TryExecute_Impersonated(executable, arguments, userToken, false, out unused, priorityClass, maxWaitMs);
   }
   finally
   {
     ImpersonationHelper.SafeCloseHandle(userToken);
   }
 }
        public void TestPriorityClassWindows()
        {
            ProcessPriorityClass priorityClass = _process.PriorityClass;

            try
            {
                _process.PriorityClass = ProcessPriorityClass.High;
                Assert.Equal(_process.PriorityClass, ProcessPriorityClass.High);

                _process.PriorityClass = ProcessPriorityClass.Normal;
                Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Normal);
            }
            finally
            {
                _process.PriorityClass = priorityClass;
            }
        }
        [Fact, PlatformSpecific(PlatformID.AnyUnix), OuterLoop] // This test requires admin elevation on Unix
        public void TestBasePriorityOnUnix()
        {
            ProcessPriorityClass originalPriority = _process.PriorityClass;

            Assert.Equal(ProcessPriorityClass.Normal, originalPriority);

            try
            {
                SetAndCheckBasePriority(ProcessPriorityClass.High, -11);
                SetAndCheckBasePriority(ProcessPriorityClass.Idle, 19);
                SetAndCheckBasePriority(ProcessPriorityClass.Normal, 0);
            }
            finally
            {
                _process.PriorityClass = originalPriority;
            }
        }
Beispiel #11
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="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>
 public static bool TryExecuteReadString(string executable, string arguments, out string result, ProcessPriorityClass priorityClass = ProcessPriorityClass.Normal, int maxWaitMs = 1000)
 {
   using (System.Diagnostics.Process process = new System.Diagnostics.Process { StartInfo = new ProcessStartInfo(executable, arguments) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true } })
   {
     process.Start();
     process.PriorityClass = priorityClass;
     using (process.StandardOutput)
     {
       result = process.StandardOutput.ReadToEnd();
       if (process.WaitForExit(maxWaitMs))
         return process.ExitCode == 0;
     }
     if (!process.HasExited)
       process.Kill();
   }
   return false;
 }
Beispiel #12
0
        static void Main(string[] args)
        {
            ProcessPriorityClass lpriority = Process.GetCurrentProcess().PriorityClass;

            Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.RealTime;


            try
            {
                mCaptureManager = new CaptureManager("CaptureManager.dll");
            }
            catch (System.Exception)
            {
                try
                {
                    mCaptureManager = new CaptureManager();
                }
                catch (System.Exception)
                {
                }
            }


            var t = new Thread(

                delegate()
            {
                try
                {
                    var lApplication = new System.Windows.Application();

                    lApplication.Run(new ControlWindow());
                }
                catch (Exception ex)
                {
                }
                finally
                {
                }
            });

            t.SetApartmentState(ApartmentState.STA);

            t.Start();
        }
Beispiel #13
0
        public encoder(int tid)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            this.tmchk.Elapsed     += new ElapsedEventHandler(this.chkjob);
            this.tmchk.AutoReset    = true;
            this.tmchk.Enabled      = true;
            this.tmchkdel.Elapsed  += new ElapsedEventHandler(this.chkjobdel);
            this.tmchkdel.AutoReset = true;
            this.tmchkdel.Enabled   = true;
            this.taskid             = tid;
            switch (this.configini.ReadString("encoder", "cpu", "").Replace("\0", ""))
            {
            case "最高":
                this.cpu_pri = ProcessPriorityClass.RealTime;
                break;

            case "高":
                this.cpu_pri = ProcessPriorityClass.High;
                break;

            case "较高":
                this.cpu_pri = ProcessPriorityClass.AboveNormal;
                break;

            case "标准":
                this.cpu_pri = ProcessPriorityClass.Normal;
                break;

            case "较低":
                this.cpu_pri = ProcessPriorityClass.BelowNormal;
                break;

            case "低":
                this.cpu_pri = ProcessPriorityClass.Idle;
                break;

            default:
                this.cpu_pri = ProcessPriorityClass.BelowNormal;
                break;
            }
            if (this.cpuCount <= 0)
            {
                this.cpuCount = 4;
            }
        }
Beispiel #14
0
        /// <summary>
        /// 同步运行程序
        /// </summary>
        /// <param name="stdInput">重定向的标准输入</param>
        /// <param name="stdOutput">重定向的标准输出</param>
        /// <param name="stdError">重定向的标准错误</param>
        /// <param name="priorityClass">进程优先级</param>
        /// <returns>进程退出码</returns>
        public int Run(string stdInput, out string stdOutput, out string stdError,
                       ProcessPriorityClass priorityClass = ProcessPriorityClass.Normal)
        {
            Process.Start();
            Process.PriorityClass = priorityClass;

            // 设置进程的处理器亲和性
            if (ProcessorAffinity.ToInt64() != 0)
            {
                Process.ProcessorAffinity = ProcessorAffinity;
            }

            Task <string> readOutputTask = new Task <string>(
                TryReadStreamToEnd, Process.StandardOutput,
                TaskCreationOptions.LongRunning);

            readOutputTask.Start();

            Task <string> readErrorTask = new Task <string>(
                TryReadStreamToEnd, Process.StandardError,
                TaskCreationOptions.LongRunning);

            readErrorTask.Start();

            try
            {
                Process.StandardInput.WriteLine(stdInput);
                if (stdInput.Length > 0 && !stdInput.EndsWith('\n')) //若输入的结尾不是换行符
                {
                    // 写入一个换行符以刷新目标进程缓冲区
                    Process.StandardInput.WriteLine();
                }
                Process.StandardInput.Close();
            }
            catch { }

            //等待读取完成
            Task.WaitAll(readOutputTask, readErrorTask);
            Process.WaitForExit();

            stdOutput = readOutputTask.Result;
            stdError  = readErrorTask.Result;

            return(Process.ExitCode);
        }
Beispiel #15
0
 static bool ChangePriority(int id, ProcessPriorityClass processPriorityClass)
 {
     try
     {
         Process ProcessChangePriority = Process.GetProcessById(id);
         ProcessChangePriority.PriorityClass = processPriorityClass;
         Console.WriteLine("prioity of {0} changed to priority {1}", ProcessChangePriority.ProcessName, processPriorityClass.ToString());
         return(true);
     }
     catch (Exception ex)
     {
         if (ex.Message == "Access is denied")
         {
             Console.WriteLine("can't Access this process");
         }
         return(false);
     }
 }
Beispiel #16
0
        public ClientConnection(string hostName, string ipAddress, int instance, ProcessPriorityClass priority, int bitSize)
        {
            IsOnline     = true;
            Jobs         = new List <Job>();
            PriorityJobs = new List <Job>();
            CurrentJob   = "";
            ActiveHours  = "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY";
            Id           = (_nextClientId++);
            HostName     = hostName;
            IPAddress    = ipAddress;
            Instance     = instance;
            Priority     = priority;
            BitSize      = bitSize;
            _lastCall.Reset();
            _lastCall.Start();

            RestoreSettings();
        }
Beispiel #17
0
        public ClientConnection(string hostName, string ipAddress, int instance, ProcessPriorityClass priority, int bitSize)
        {
            IsOnline = true;
            Jobs = new List<Job>();
            PriorityJobs = new List<Job>();
            CurrentJob = "";
            ActiveHours = "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY";
            Id = (_nextClientId++);
            HostName = hostName;
            IPAddress = ipAddress;
            Instance = instance;
            Priority = priority;
            BitSize = bitSize;
            _lastCall.Reset();
            _lastCall.Start();

            RestoreSettings();
        }
Beispiel #18
0
 public WatchedProcess(
     string processName,
     string commandLine,
     int startTimeSeconds,
     int endTimeSeconds,
     Action <string> reportProcessStatus,
     IList <DateTime> restartTimes = null,
     ProcessPriorityClass priority = ProcessPriorityClass.High)
 {
     ProcessName = processName;
     CommandLine = commandLine.Trim();
     SplitCommandLine();
     StartTimeSeconds     = startTimeSeconds;
     EndTimeSeconds       = endTimeSeconds;
     _reportProcessStatus = reportProcessStatus;
     ProcessPriority      = priority;
     RestartTimes         = restartTimes ?? new List <DateTime>();
 }
Beispiel #19
0
        public static BCPExportResult Run(BCPExportInfo pBCPExportInfo)
        {
            string _output = string.Empty;

            try {
                string _exeName = "bcp.exe";

                //_startInfo.FileName = @"C:\TIMOK.DEPLOYMENT\Rbr-v2.0.5.0\Diagrams\205\Init_data\TEST __CDRDb_205_Export_8_Data.bat";
                //bcp "SELECT * FROM CDRDb_205.dbo.CDR WHERE timok_date >= 200421400 AND timok_date < 200424500" queryout "C:\Timok\Rbr\SqlDb\ExportedData\205\CDR_200408_TEST.txt" -c -S(local)\TRBR -T
                string _args = string.Empty;           // + //@"SELECT TOP 70000 * FROM CDRDb_205.dbo.CDR WHERE timok_date >= 200421400 AND timok_date < 200424500" +
                _args += '"' + pBCPExportInfo.SQL + '"';
                _args += " queryout ";                 //@"C:\Timok\Rbr\SqlDb\ExportedData\205\CDR_200408_TEST.txt" +
                _args += '"' + pBCPExportInfo.FilePath + '"';
                if (pBCPExportInfo.Delimeter == null || pBCPExportInfo.Delimeter.Trim().Length == 0)
                {
                    //_args += "-t\t";//default
                }
                else
                {
                    _args += " -t" + pBCPExportInfo.Delimeter;
                }

                _args += @" -c ";
                _args += " -S" + pBCPExportInfo.Server;                 //(local)\TRBR -T";
                if (pBCPExportInfo.TrustedConnection)
                {
                    _args += " -T";
                }
                else
                {
                    _args += " -U" + '"' + pBCPExportInfo.User + '"';                   // -U"Jane Doe"
                    _args += " -P" + '"' + pBCPExportInfo.Pwd + '"';                    // -P"go dba"
                }

                ProcessPriorityClass _priorityClass = ProcessPriorityClass.BelowNormal;

                _output = CMDHelper.Run(_exeName, _args, _priorityClass, pBCPExportInfo.TimeoutSeconds);
            }
            catch (Exception e) {
                throw new ApplicationException("An error occurred running BCP.", e);
            }

            return(processOutput(_output, pBCPExportInfo));
        }
Beispiel #20
0
        //apply based on profile
        public void setNiceProfile(SettingsManager sm)
        {
            sm.IPClocked = true;

            Process[] plist = Process.GetProcesses();


            //simple check to see if theres new processes or not
            int ctemp = plist.Count();

            if (count != ctemp)
            {
                count = ctemp;

                plist.ToList().ForEach(proc =>
                {
                    int temp = -1;
                    foreach (string name in sm.special_programs.configList.Keys)
                    {
                        if (proc.ProcessName.ToLower().Contains(name.ToLower()))
                        {
                            temp = (int)sm.special_programs.configList[name];
                        }
                    }
                    if (temp == -1)
                    {
                        return;             //not in my list
                    }
                    try
                    {
                        ProcessPriorityClass temp2 =
                            (ProcessPriorityClass)sm.programs_running_cfg_nice.configList[temp];
                        if (proc.PriorityClass != temp2)
                        {
                            log.WriteLog("setting niceness: " + proc.ProcessName + " to " + temp2.ToString());
                            proc.PriorityClass = temp2;
                        }
                    }
                    catch (Exception) { }
                });
            }

            sm.IPClocked = false;
        }
        private byte PriorityNumber(ProcessPriorityClass priority)
        {
            switch (priority)
            {
            case ProcessPriorityClass.Idle: return(0);

            case ProcessPriorityClass.BelowNormal: return(1);

            case ProcessPriorityClass.Normal: return(2);

            case ProcessPriorityClass.AboveNormal: return(3);

            case ProcessPriorityClass.High: return(4);

            case ProcessPriorityClass.RealTime: return(5);

            default: throw new Exception("Невозможно определить приоритет.");
            }
        }
        public void DsfExecuteCommandLineActivity_GetForEachInputs_WhenHasExpression_ReturnsInputList()
        {
            //------------Setup for test--------------------------
            const ProcessPriorityClass commandPriority = ProcessPriorityClass.RealTime;
            var command1 = "\"" + TestContext.DeploymentDirectory + "\\ConsoleAppToTestExecuteCommandLineActivity.exe\" output";
            var act      = new DsfExecuteCommandLineActivity {
                CommandFileName = command1, CommandResult = "[[OutVar1]]", CommandPriority = commandPriority
            };

            //------------Execute Test---------------------------
            var dsfForEachItems = act.GetForEachInputs();

            //------------Assert Results-------------------------
            Assert.AreEqual(2, dsfForEachItems.Count);
            Assert.AreEqual(command1, dsfForEachItems[0].Name);
            Assert.AreEqual(command1, dsfForEachItems[0].Value);
            Assert.AreEqual(commandPriority.ToString(), dsfForEachItems[1].Name);
            Assert.AreEqual(commandPriority.ToString(), dsfForEachItems[1].Value);
        }
Beispiel #23
0
        private void SetPriority(string priority)
        {
            settings.ProcessPriority = priority;
            ProcessPriorityClass ppc = ProcessPriorityClass.Normal;

            switch (priority)
            {
            case "High": ppc = ProcessPriorityClass.High; settings.ProcessPriorityHigh = true; break; settings.ProcessPriorityAboveNormal = false; settings.ProcessPriorityNormal = false; break;

            case "Above Normal": ppc = ProcessPriorityClass.AboveNormal; settings.ProcessPriorityHigh = false; settings.ProcessPriorityAboveNormal = true; break; settings.ProcessPriorityNormal = false; break;

            case "Normal": ppc = ProcessPriorityClass.Normal; settings.ProcessPriorityHigh = false; settings.ProcessPriorityAboveNormal = false; settings.ProcessPriorityNormal = true; break;
            }
            //settings.Save();
            using (Process p = Process.GetCurrentProcess())
            {
                p.PriorityClass = ppc;
            }
        }
Beispiel #24
0
        public static String StartProcess(String FileName, String Arguments, ProcessPriorityClass Priority)
        {
            Process p = new Process();

            p.StartInfo.CreateNoWindow         = false;
            p.StartInfo.UseShellExecute        = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.WindowStyle            = ProcessWindowStyle.Hidden;
            p.StartInfo.FileName  = FileName;
            p.StartInfo.Arguments = Arguments;
            p.Start();
            p.PriorityClass = Priority;

            String output = p.StandardOutput.ReadToEnd();

            p.WaitForExit();

            return(output);
        }
Beispiel #25
0
        /// <summary>
        /// Retrieves the desired priority for the new process invocation. (Normal if none is set)
        /// </summary>
        /// <param name="launchNode">The node containing all settings for </param>
        /// <returns>The desired priority for this execution</returns>
        private static ProcessPriorityClass RetrievePriority(XmlNode launchNode)
        {
            ProcessPriorityClass priority = ProcessPriorityClass.Normal;

            if (launchNode != null)
            {
                string priorityStr = GetAttribute("value", launchNode.SelectSingleNode("PRIORITY"),
                                                  ProcessPriorityClass.Normal.ToString());

                switch (priorityStr)
                {
                case "Normal":
                    priority = ProcessPriorityClass.Normal;
                    break;

                case "AboveNormal":
                    priority = ProcessPriorityClass.AboveNormal;
                    break;

                case "BelowNormal":
                    priority = ProcessPriorityClass.BelowNormal;
                    break;

                case "High":
                    priority = ProcessPriorityClass.High;
                    break;

                case "Idle":
                    priority = ProcessPriorityClass.Idle;
                    break;

                case "RealTime":
                    priority = ProcessPriorityClass.RealTime;
                    break;

                default:
                    priority = ProcessPriorityClass.Normal;
                    break;
                }
            }
            return(priority);
        }
Beispiel #26
0
        public static ThreadPriority ToThreadPriority(this ProcessPriorityClass priority)
        {
            switch (priority)
            {
            case ProcessPriorityClass.AboveNormal:
                return(ThreadPriority.AboveNormal);

            case ProcessPriorityClass.BelowNormal:
                return(ThreadPriority.BelowNormal);

            case ProcessPriorityClass.High:
                return(ThreadPriority.Highest);

            case ProcessPriorityClass.Idle:
                return(ThreadPriority.Lowest);

            default:
                return(ThreadPriority.Normal);
            }
        }
Beispiel #27
0
        private static IDisposable SpeedTestOptimizer()
        {
            Process process = Process.GetCurrentProcess();
            ProcessPriorityClass lastPriorityClass = process.PriorityClass;
            GCLatencyMode        lastLatencyMode   = GCSettings.LatencyMode;

            return(new DisposableDelegate
                   (
                       initializer: () =>
            {
                process.PriorityClass = ProcessPriorityClass.RealTime;
                GCSettings.LatencyMode = GCLatencyMode.SustainedLowLatency;
            },
                       disposer: () =>
            {
                GCSettings.LatencyMode = lastLatencyMode;
                process.PriorityClass = lastPriorityClass;
            }
                   ));
        }
        static void CorrectProcessWithName(string processName, ProcessPriorityClass desiredPriorityClass)
        {
            var processes = Process.GetProcessesByName(processName);

            if (processes.Length == 0)
            {
                Console.WriteLine("Did not find process {0}", processName);
                return;
            }

            foreach (var process in processes)
            {
                var oldPriorityClass = process.PriorityClass;
                if (oldPriorityClass != desiredPriorityClass)
                {
                    process.PriorityClass = desiredPriorityClass;
                    Console.WriteLine("{0}: Corrected process {1} priority from {2} to {3}", DateTime.Now, process, oldPriorityClass, desiredPriorityClass);
                }
            }
        }
Beispiel #29
0
        public static bool TrySetPriorityClass(this Process process, ProcessPriorityClass priorityClass)
        {
            if (!s_settingPrioritySupported)
            {
                return(false);
            }

            try
            {
                process.PriorityClass = priorityClass;
                return(true);
            }
            catch (Exception e) when(e is PlatformNotSupportedException || e is Win32Exception)
            {
                // the runtime does not support changing process priority
                s_settingPrioritySupported = false;

                return(false);
            }
        }
Beispiel #30
0
        private void Button_Click_2(object sender, RoutedEventArgs e)//Save
        {
            ProcessPriorityClass priorityClass = (ProcessPriorityClass)PriorityCombo.SelectionBoxItem;

            try
            {
                if (pro.PriorityClass != priorityClass)
                {
                    pro.PriorityClass = priorityClass;
                }
            }
            catch (Exception)
            {
            }

            MainWindow mainWindow = new MainWindow();

            mainWindow.Show();
            this.Close();
        }
Beispiel #31
0
        //apply nice per process
        public void setProcNice(Process proc, SettingsManager sm)
        {
            int temp = checkInList(proc, sm);

            if (temp == -1)
            {
                return;             //not in my list
            }
            try
            {
                ProcessPriorityClass temp2 =
                    (ProcessPriorityClass)sm.programs_running_cfg_nice.configList[temp];
                if (proc.PriorityClass != temp2)
                {
                    log.WriteLog("setting niceness: " + proc.ProcessName + " to " + temp2.ToString());
                    proc.PriorityClass = temp2;
                }
            }
            catch (Exception) { }
        }
Beispiel #32
0
 public FFMpegCommand(
     string pathToFfMpegExe,
     string command,
     Action <double, double, int> progressCallback,
     IObservable <double> stopSignal,
     ProcessPriorityClass processPriorityClass,
     double?commandDurationInSeconds = null,
     bool ignoreError = false)
 {
     this.pathToFfMpegExe      = pathToFfMpegExe;
     this.command              = command;
     this.progressCallback     = progressCallback;
     this.stopSignal           = stopSignal;
     this.processPriorityClass = processPriorityClass;
     this.ignoreError          = ignoreError;
     if (commandDurationInSeconds.HasValue)
     {
         this.commandDuration = TimeSpan.FromSeconds(commandDurationInSeconds.Value);
     }
 }
Beispiel #33
0
 public static void SetProcessPriority(IntPtr handle, ProcessPriorityClass priority)
 {
     if (IsVistaOrNot)
     {
         int prioIO     = VistaStuff.PRIORITY_IO_NORMAL;
         int prioMemory = VistaStuff.PRIORITY_MEMORY_NORMAL;
         if (priority == ProcessPriorityClass.Idle || priority == ProcessPriorityClass.BelowNormal)
         {
             prioIO     = VistaStuff.PRIORITY_IO_LOW;
             prioMemory = VistaStuff.PRIORITY_MEMORY_LOW;
             SetPriorityClass(handle, PROCESS_MODE_BACKGROUND_BEGIN);
         }
         else
         {
             SetPriorityClass(handle, PROCESS_MODE_BACKGROUND_END);
         }
         NtSetInformationProcess(handle, PROCESS_INFORMATION_IO_PRIORITY, ref prioIO, Marshal.SizeOf(prioIO));
         NtSetInformationProcess(handle, PROCESS_INFORMATION_MEMORY_PRIORITY, ref prioMemory, Marshal.SizeOf(prioMemory));
     }
 }
Beispiel #34
0
        public void TestBasePriorityOnUnix()
        {
            CreateDefaultProcess();

            ProcessPriorityClass originalPriority = _process.PriorityClass;

            Assert.Equal(ProcessPriorityClass.Normal, originalPriority);
            SetAndCheckBasePriority(ProcessPriorityClass.Idle, 19);

            try
            {
                SetAndCheckBasePriority(ProcessPriorityClass.Normal, 0);
                SetAndCheckBasePriority(ProcessPriorityClass.High, -11);
                _process.PriorityClass = originalPriority;
            }
            catch (Win32Exception ex)
            {
                Assert.True(!PlatformDetection.IsSuperUser, $"Failed even though superuser {ex.ToString()}");
            }
        }
Beispiel #35
0
        private static bool TrySetPriority(
            int id,
            ProcessPriorityClass selected,
            Options options
            )
        {
            try
            {
                using var p = Process.GetProcessById(id);
                var originalClass = p.PriorityClass;
                if (options.Dummy)
                {
                    options.Logger.Log($"Process #{id} ({p.ProcessName}) has priority: {originalClass}");
                    return(true);
                }

                if (originalClass == selected)
                {
                    if (options.Verbose)
                    {
                        options.Logger.Status($"pid [{id}] already has priority {selected}");
                    }

                    return(true);
                }

                p.PriorityClass = selected;
                if (options.Verbose)
                {
                    options.Logger.Status($"altered priority of pid [{id}] from {originalClass} to {selected}");
                    options.Logger.AfterStatus();
                }

                return(true);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine($"Can't set priority on {id}: {ex.Message}");
                return(false);
            }
        }
        public static void ApplyMyPriority(ProcessPriorityClass priority)
        {
            // AppVeyor: Windows - OK, linux: need sudo
            // Travis: OSX 10.10 & 10.14 - need sudo, Ubuntu - ?!
            bool isOk = SetMyProcessPriority(priority);

            if (!isOk)
            {
                Console.WriteLine(
                    $"WARNING! Process priority can not be changed. Permission is required");
            }

            if (priority == ProcessPriorityClass.AboveNormal)
            {
                Thread.CurrentThread.Priority = ThreadPriority.AboveNormal;
            }
            else if (priority == ProcessPriorityClass.Normal)
            {
                Thread.CurrentThread.Priority = ThreadPriority.Normal;
            }
            else if (priority == ProcessPriorityClass.BelowNormal)
            {
                Thread.CurrentThread.Priority = ThreadPriority.BelowNormal;
            }
            else if (priority == ProcessPriorityClass.High)
            {
                Thread.CurrentThread.Priority = ThreadPriority.Highest;
            }
            else if (priority == ProcessPriorityClass.RealTime)
            {
                Thread.CurrentThread.Priority = ThreadPriority.Highest;
            }
            else if (priority == ProcessPriorityClass.Idle)
            {
                Thread.CurrentThread.Priority = ThreadPriority.Lowest;
            }
            else
            {
                throw new NotSupportedException($"Priority {priority} is not supported for a thread");
            }
        }
Beispiel #37
0
        public TimokProcess(string pWorkingDir, string pFileName, string pArguments, ProcessPriorityClass pPriority)
        {
            try {
                priority = pPriority;

                StartInfo.WorkingDirectory = pWorkingDir;
                StartInfo.FileName         = pFileName;
                StartInfo.Arguments        = pArguments;
                if (!string.IsNullOrEmpty(StartInfo.WorkingDirectory) && !string.IsNullOrEmpty(StartInfo.FileName))
                {
                    Enabled = true;
                }
                else
                {
                    Enabled = false;
                }
            }
            catch (Exception _ex) {
                throw new ApplicationException("TimokProcess.Ctor | Exception:", _ex);
            }
        }
Beispiel #38
0
        public void Process_BasePriority()
        {
            ProcessPriorityClass originalPriority = _process.PriorityClass;

            Assert.Equal(ProcessPriorityClass.Normal, originalPriority);

            if (global::Interop.IsWindows)
            {
                try
                {
                    //SetAndCheckBasePriority(ProcessPriorityClass.RealTime, 24);
                    SetAndCheckBasePriority(ProcessPriorityClass.High, 13);
                    SetAndCheckBasePriority(ProcessPriorityClass.Idle, 4);
                    SetAndCheckBasePriority(ProcessPriorityClass.Normal, 8);
                }
                finally
                {
                    _process.PriorityClass = originalPriority;
                }
            }
        }
Beispiel #39
0
 internal Encoder(string script, string output, string encoder, string commandLine, bool sendHeader, int HeaderType, int ChannelMask, bool bKeepOutput,
                  int iPriority)
 {
     this.m_script          = script;
     this.m_output          = output;
     this.m_encoder         = encoder;
     this.m_commandLine     = commandLine;
     this.m_sendHeader      = sendHeader;
     this.m_HeaderType      = HeaderType;
     this.m_ChannelMask     = ChannelMask;
     this.m_bKeepOutput     = bKeepOutput;
     this.m_processPriority = (ProcessPriorityClass)iPriority;
     m_process = null;
     if (null != m_encoder)
     {
         if (0 == m_encoder.Length)
         {
             m_encoder = null;
         }
     }
 }
Beispiel #40
0
 private void MainCryptoolWindow_StateChanged(object sender, EventArgs e)
 {
     if (WindowState == WindowState.Minimized)
     {
         if (closingCausedMinimization)
         {
             ShowInTaskbar = false;
             notifyIcon.ShowBalloonTip(1000 * 5, Properties.Resources.Information, Properties.Resources.Cryptool_2_0_has_been_backgrounded_due_to_running_tasks_, ToolTipIcon.Info);
             oldPriority = Process.GetCurrentProcess().PriorityClass;
             Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.Idle;
         }
         closingCausedMinimization = false;
     }
     else
     {
         oldWindowState = WindowState;
         ShowInTaskbar  = true;
         Visibility     = Visibility.Visible;
         Process.GetCurrentProcess().PriorityClass = oldPriority;
     }
 }
Beispiel #41
0
        public void Run(ProcessEx process, ProcessPriorityClass priority)
        {
            if (this.Status.InUse)
            throw new InvalidOperationException("Current core is running another process");

              if (process == null)
            throw new ArgumentNullException("Process can not be null");

              this.Process = process;
              this.Process.ExecutingCore = this;

              //bind event
              this.Process.Exited += Process_Exited;

              this.Process.Start();
              this.Process.Status = ProcessExecutionStatus.Running;
              this.Process.PriorityClass = priority;
              this.Status.InUse = true;

              //TODO set affinity
              this.Process.ProcessorAffinity = (IntPtr) (int) Math.Pow(2, this.Status.Index);
        }
Beispiel #42
0
        public void RegistSchedule(string serviceName,ProcessPriorityClass Priority,string FilePath,string args)
        {
            using (TaskService task= new TaskService())
            {
                string SchedulerName= "GISHitpanDBManager"+Guid.NewGuid().ToString();
                using(TaskDefinition def = task.NewTask())
                {
                    //일반
                    def.Principal.DisplayName = serviceName;
                    def.Principal.UserId=string.Format("{0}\\{1}",Environment.UserDomainName,Environment.UserName);
                    def.Principal.LogonType=TaskLogonType.InteractiveToken;
                    def.Principal.RunLevel=TaskRunLevel.Highest;
                    def.Triggers.Add( new LogonTrigger());
                    //조건
                    def.Settings.MultipleInstances=TaskInstancesPolicy.IgnoreNew;
                    def.Settings.DisallowStartIfOnBatteries=false;
                    def.Settings.StopIfGoingOnBatteries=false;
                    def.Settings.AllowHardTerminate=false;
                    def.Settings.StartWhenAvailable=true;
                    def.Settings.RunOnlyIfNetworkAvailable=false;
                    def.Settings.IdleSettings.StopOnIdleEnd=false;
                    def.Settings.IdleSettings.RestartOnIdle=false;
                    //설정
                    def.Settings.AllowDemandStart=false;
                    def.Settings.Enabled=true;
                    def.Settings.Hidden=false;
                    def.Settings.RunOnlyIfIdle=false;
                    def.Settings.ExecutionTimeLimit=TimeSpan.Zero;
                    def.Settings.Priority = Priority;
                    //동작
                    def.Actions.Add(FilePath, args);
                    //등록
                    task.RootFolder.RegisterTaskDefinition(SchedulerName,def);
                }

            }
        }
Beispiel #43
0
 /// <summary>
 /// Executes the <paramref name="executable"/> and waits a maximum time of <paramref name="maxWaitMs"/> for completion. If the process doesn't end in 
 /// this time, it gets aborted. This helper method automatically decides if an impersonation should be done, depending on the current identity's 
 /// <see cref="TokenImpersonationLevel"/>.
 /// </summary>
 /// <param name="executable">Program to execute</param>
 /// <param name="arguments">Program arguments</param>
 /// <param name="priorityClass">Process priority</param>
 /// <param name="maxWaitMs">Maximum time to wait for completion</param>
 /// <returns><c>true</c> if process was executed and finished correctly</returns>
 public static bool TryExecute_AutoImpersonate(string executable, string arguments, ProcessPriorityClass priorityClass = ProcessPriorityClass.Normal, int maxWaitMs = INFINITE)
 {
   return IsImpersonated ?
     TryExecute_Impersonated(executable, arguments, priorityClass, maxWaitMs) :
     TryExecute(executable, arguments, priorityClass, maxWaitMs);
 }
Beispiel #44
0
 /// <summary>
 /// Executes the <paramref name="executable"/> and waits a maximum time of <paramref name="maxWaitMs"/> for completion. 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="priorityClass">Process priority</param>
 /// <param name="maxWaitMs">Maximum time to wait for completion</param>
 /// <returns><c>true</c> if process was executed and finished correctly</returns>
 public static bool TryExecute(string executable, string arguments, ProcessPriorityClass priorityClass = ProcessPriorityClass.Normal, int maxWaitMs = INFINITE)
 {
   string unused;
   return TryExecute(executable, arguments, false, out unused, priorityClass, maxWaitMs);
 }
Beispiel #45
0
    /// <summary>
    /// Executes the <paramref name="executable"/> and waits a maximum time of <paramref name="maxWaitMs"/> for completion. If the process doesn't end in 
    /// this time, it gets aborted. This method tries to impersonate the interactive user and run the process under its identity.
    /// </summary>
    /// <param name="executable">Program to execute</param>
    /// <param name="arguments">Program arguments</param>
    /// <param name="token">User token to run process</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><c>true</c> if process was executed and finished correctly</returns>
    private static bool TryExecute_Impersonated(string executable, string arguments, IntPtr token, bool redirectInputOutput, out string result, ProcessPriorityClass priorityClass = ProcessPriorityClass.Normal, int maxWaitMs = INFINITE)
    {
      // TODO: code is 99% redundant to TryExecute, refactor Process/ImpersonationProcess and Start/StartAsUser!
      StringBuilder outputBuilder = new StringBuilder();
      using (ImpersonationProcess process = new ImpersonationProcess { StartInfo = new ProcessStartInfo(executable, arguments) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = redirectInputOutput } })
      {
        if (redirectInputOutput)
        {
          // Set UTF-8 encoding for standard output.
          process.StartInfo.StandardOutputEncoding = CONSOLE_ENCODING;
          // Enable raising events because Process does not raise events by default.
          process.EnableRaisingEvents = true;
          // Attach the event handler for OutputDataReceived before starting the process.
          process.OutputDataReceived += (sender, e) => outputBuilder.Append(e.Data);
        }
        process.StartAsUser(token);
        process.PriorityClass = priorityClass;

        if (redirectInputOutput)
          process.BeginOutputReadLine();

        if (process.WaitForExit(maxWaitMs))
        {
          result = RemoveEncodingPreamble(outputBuilder.ToString());
          return process.ExitCode == 0;
        }
        if (!process.HasExited)
          process.Kill();
      }
      result = null;
      return false;
    }
Beispiel #46
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="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>
 public static bool TryExecuteReadString_AutoImpersonate(string executable, string arguments, out string result, ProcessPriorityClass priorityClass = ProcessPriorityClass.Normal, int maxWaitMs = 1000)
 {
   return IsImpersonated ?
     TryExecuteReadString_Impersonated(executable, arguments, out result, priorityClass, maxWaitMs) :
     TryExecuteReadString(executable, arguments, out result, priorityClass, maxWaitMs);
 }
Beispiel #47
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="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>
 public static bool TryExecuteReadString(string executable, string arguments, out string result, ProcessPriorityClass priorityClass = ProcessPriorityClass.Normal, int maxWaitMs = 1000)
 {
   return TryExecute(executable, arguments, true, out result, priorityClass, maxWaitMs);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ProcessInfo" /> class.	
 /// </summary>
 /// <param name="filename">The filename.</param>
 /// <param name="arguments">The arguments.</param>
 /// <param name="workingDirectory">The working directory.</param>
 /// <param name="priority">The priority.</param>
 /// <remarks></remarks>
 public ProcessInfo(string filename, PrivateArguments arguments, string workingDirectory, ProcessPriorityClass priority) :
     this(filename, arguments, workingDirectory, priority, null){}
Beispiel #49
0
 private ProcessInfo NewProcessInfo(string args, IIntegrationResult result, ProcessPriorityClass priority, int[] successExitCodes)
 {
     Log.Info(string.Concat("[Git] Calling git ", args));
     var processInfo = new ProcessInfo(Executable, args, BaseWorkingDirectory(result), priority,
                                               successExitCodes);
     //processInfo.StreamEncoding = Encoding.UTF8;
     return processInfo;
 }
Beispiel #50
0
        public virtual void SetPriorityClass(ProcessPriorityClass c)
        {
            var extendedLimit = GetJobLimits();

            extendedLimit.BasicLimitInformation.LimitFlags |= NativeMethods.JobObjectLimit.PriorityClass;
            extendedLimit.BasicLimitInformation.PriorityClass = (uint)c;

            SetJobLimits(extendedLimit);
        }
Beispiel #51
0
        public void QueueProcess(ProcessPriorityClass prc, params ProcessEx[] processes)
        {
            if (processes == null)
            throw new ArgumentNullException("Processes can not be null");

              foreach (var item in processes)
              {
            this.QueueProcess(item, prc);
              }
        }
Beispiel #52
0
 /// <summary>
 /// Queues the process.
 /// </summary>
 /// <param name="process">The process to enqueue.</param>
 /// <param name="prc">process priority.</param>
 public void QueueProcess(ProcessEx process, ProcessPriorityClass prc)
 {
     lock (_queueLock)
       {
     this._processQueue.Enqueue(new KeyValuePair<ProcessEx, ProcessPriorityClass>(process, prc));
     process.Status = ProcessExecutionStatus.Queued;
       }
 }
Beispiel #53
0
 private void SetProcessPriority(ProcessPriorityClass priority)
 {
     try
     {
         using (var phandle = new ProcessHandle(processSelectedPid, ProcessAccess.SetInformation))
             phandle.SetPriorityClass(priority);
     }
     catch (Exception ex)
     {
         PhUtils.ShowException("Unable to set process priority", ex);
     }
 }
 private void UpdateSpringPriorityMenu(ToolStripMenuItem menu, ProcessPriorityClass priority)
 {
   foreach (ToolStripMenuItem c in menu.DropDownItems) {
     // list through priorities
     if (c.Text == priority.ToString()) {
       // we found priority, set it up
       c.Checked = true;
     } else c.Checked = false;
   }
 }
Beispiel #55
0
 public SetPriorityJob(ProcessPriorityClass priority)
 {
     _priority = priority;
 }
Beispiel #56
0
        public virtual void Run()
        {
                
            //_success = false; //initial state to be defined by each inheriting class depending on it's handlers, we only update error conditions in this routine
            Process Proc = null;
            DateTime ExecutionStartTime;

            // Last thing to check, for custom commands, this will log an error and exit
            if (!File.Exists(_ApplicationPath))
            {
                _jobStatus.ErrorMsg = "Application File Not Found";
                _jobLog.WriteEntry(this, _jobStatus.ErrorMsg + " : " + _ApplicationPath, Log.LogEntryType.Error);
                _jobStatus.PercentageComplete = 0;
                _success = false;
                return;
            }

            if (_Parameters.Length > 8192)
                _jobLog.WriteEntry(this, Localise.GetPhrase("Warning - command parameters exceeding 8192 characters.  This may fail on some systems such as Windows XP"), Log.LogEntryType.Warning);

            // Reset any progress counters
            _jobStatus.PercentageComplete = 0;
            _jobStatus.ETA = Localise.GetPhrase("Working") + "..."; //some processes like ReMuxSupp don't update perc, put a default message

            // Check if job has been cancelled, needed for some long running functions called Base
            if (_jobStatus.Cancelled)
            {
                _jobStatus.ErrorMsg = "Job cancelled, killing process";
                _jobLog.WriteEntry(this, _jobStatus.ErrorMsg, Log.LogEntryType.Error);
                _success = false; //process has been terminated
                return;
            }

            try
            {
                if (_HangPeriod > 0)
                    _LastTick = DateTime.Now;

                _jobLog.WriteEntry(this, "Launching process " + _ApplicationPath, Log.LogEntryType.Debug);
                _jobLog.WriteEntry(this, "Process arguments " + _Parameters, Log.LogEntryType.Debug);

                if (GlobalDefs.IsEngineRunningAsService) // these params only make sense when running as a service
                    _jobLog.WriteEntry(this, "UI Session Admin Process : " + _uiAdminSessionProcess.ToString(), Log.LogEntryType.Debug);

                //Start the process
                ExecutionStartTime = DateTime.Now;

                // Check if we need to run a UISession process - It can only be run from a service, if we are running from a non service console, we don't need this
                // Apps like handbrake with hardware accelleration cannot run from a non UI session in windows (even in Windows 8 there are limitations with ffmpeg and OpenCL from Session 0) due to unavailability of hardware (OpenCL) API's in NonUI sessions mode
                // These apps needs to be started in a UI session separately to run
                // Check if we are running as a Service (Session 0 non UI Interactive) and if the user forcing use of UI Session 1
                bool checkUICompliance = (GlobalDefs.IsEngineRunningAsService && _uiAdminSessionProcess);
                if (checkUICompliance)
                {
                    _jobLog.WriteEntry(this, "Starting process as a UISession process with Admin privileges. This requires atleast 1 user to be logged into the system (remote desktop or locally)", Log.LogEntryType.Debug);
                    uint procId = AppProcess.StartAppWithAdminPrivilegesFromNonUISession(_ApplicationPath, _Parameters, true, OutputHandler, _showWindow, _jobLog);
                    if (procId == 0)
                    {
                        _jobLog.WriteEntry(this, "Unable to create UI Session process with Admin Privileges from NonUI Session. Is any user logged on?", Log.LogEntryType.Warning);
                        _jobLog.WriteEntry(this, "Retrying process creation as a NonUI Session process with Admin privileges", Log.LogEntryType.Warning);
                        _jobLog.WriteEntry(this, "Some functions like hardware encoding may not work in this mode", Log.LogEntryType.Warning);
                        Proc = null;
                    }
                    else
                        Proc = Process.GetProcessById((int)procId); // Get the process identifier
                }
                
                // Create the process if it hasn't already been created
                if(Proc == null)
                {
                    //Set up the process
                    Proc = new Process();
                    Proc.StartInfo.FileName = _ApplicationPath;
                    Proc.StartInfo.Arguments = _Parameters;
                    if (_showWindow)
                    {
                        Proc.StartInfo.CreateNoWindow = false; // for custom apps we create a window
                        Proc.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
                    }
                    else
                    {
                        Proc.StartInfo.CreateNoWindow = true;
                        Proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    }
                    Proc.StartInfo.WorkingDirectory = Path.GetDirectoryName(_ApplicationPath);
                    Proc.StartInfo.RedirectStandardOutput = true;
                    Proc.StartInfo.RedirectStandardError = true;
                    Proc.StartInfo.UseShellExecute = false; // always false else error handlers break
                    Proc.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
                    Proc.ErrorDataReceived += new DataReceivedEventHandler(OutputHandler);

                    Proc.Start(); // First start the process else we get an exception
                    Proc.BeginOutputReadLine();
                    Proc.BeginErrorReadLine();
                }

                _jobLog.WriteEntry(this, "Setting process priority to " + GlobalDefs.Priority.ToString(), Log.LogEntryType.Debug);
                lastPriority = GlobalDefs.Priority; // Set it up
                Proc.PriorityClass = GlobalDefs.Priority; // Set the CPU Priority
                IOPriority.SetPriority(Proc.Handle, GlobalDefs.IOPriority); // Set the IO Priority

                try
                {
                    if (MCEBuddyConf.GlobalMCEConfig.GeneralOptions.CPUAffinity != (IntPtr)0)
                    {
                        _jobLog.WriteEntry(this, "Setting CPU affinity to -> " + MCEBuddyConf.GlobalMCEConfig.GeneralOptions.CPUAffinity.ToString("d"), Log.LogEntryType.Debug);
                        Proc.ProcessorAffinity = MCEBuddyConf.GlobalMCEConfig.GeneralOptions.CPUAffinity;
                    }
                }
                catch (Exception e)
                {
                    _jobLog.WriteEntry(this, "Error trying to set CPU affinity to -> " + MCEBuddyConf.GlobalMCEConfig.GeneralOptions.CPUAffinity.ToString("d") + "\n" + e.ToString(), Log.LogEntryType.Warning);
                }
            }
            catch (Exception Ex)
            {
                _jobStatus.ErrorMsg = "Unable to start process";
                _jobLog.WriteEntry(this, _jobStatus.ErrorMsg + "\r\n" + Ex.Message, Log.LogEntryType.Error);
                _success = false; //process did not start
                return; // Exit now or we get an exception
            }

            //Wait for an end
            while ((!Proc.HasExited))
            {
                try
                {
                    if (!_ignoreSuspend) // for some processes like ffmpegMediaInfo initiated by UI, we cannot block since it will hang the application
                    {
                        if (!isSuspended && GlobalDefs.Pause) // Check if process has to be suspended (if not already)
                        {
                            _jobLog.WriteEntry(this, "Suspending process", Log.LogEntryType.Information);
                            IOPriority.SuspendProcess(Proc.Id);
                            _jobLog.Flush(); // Flush the pending writes
                            isSuspended = true;
                        }

                        if (isSuspended && !GlobalDefs.Pause) // Check if we need to resume the process
                        {
                            _jobLog.WriteEntry(this, "Resuming process", Log.LogEntryType.Information);
                            isSuspended = false;
                            _percentageHistory.Clear(); // Lose the history and start from here
                            IOPriority.ResumeProcess(Proc.Id);
                        }
                    }

                    if (lastPriority != GlobalDefs.Priority) // Check if the priority was changed and if so update it
                    {
                        _jobLog.WriteEntry(this, "Process priority changed", Log.LogEntryType.Information);
                        lastPriority = GlobalDefs.Priority;
                        Proc.PriorityClass = GlobalDefs.Priority;
                        IOPriority.SetPriority(Proc.Handle, GlobalDefs.IOPriority); // First set the CPU priority
                    }
                }
                catch { } //incase process exits in the background - not an issue, just avoid a crash

                if (_jobStatus.Cancelled) // if job has been cancelled kill the process
                {
                    try
                    {
                        Proc.Kill();
                        _jobStatus.ErrorMsg = "Job cancelled, killing process";
                        _jobLog.WriteEntry(_jobStatus.ErrorMsg, Log.LogEntryType.Error);
                        _success = false; //process has been terminated
                    }
                    catch (Exception Ex)
                    {
                        _jobStatus.ErrorMsg = "Job cancelled, unable to kill process";
                        _jobLog.WriteEntry(_jobStatus.ErrorMsg, Log.LogEntryType.Error);
                        _jobLog.WriteEntry(Ex.Message, Log.LogEntryType.Warning);
                        _success = false; //process has been terminated
                    }
                    break;
                }

                if (_unrecoverableError)
                {
                    _jobLog.WriteEntry("Unrecoverable error encountered. Process likely hung, killing it", Log.LogEntryType.Error);
                    _success = false;
                    break;
                }

                if (isSuspended)
                    _LastTick = DateTime.Now; // Since during suspension there will be no output it shouldn't terminate the process

                if ((_HangPeriod > 0) && (DateTime.Now > _LastTick.AddSeconds(_HangPeriod)))
                {
                    _jobLog.WriteEntry("No response from process for " + _HangPeriod + " seconds, process likely hung - killing it", Log.LogEntryType.Error);
                    _success = false;
                    break;
                }

                System.Threading.Thread.Sleep(100); // sleep and check again
            }

            if (!_jobStatus.Cancelled)
                System.Threading.Thread.Sleep(2000);    //Allow the last set of messages to be written

            if (!Proc.HasExited) // If we broke out of the loop, somethign bad happened
            {
                try
                {
                    Proc.Kill();
                    _jobStatus.ErrorMsg = "Process hung, killing process";
                    _jobLog.WriteEntry(_jobStatus.ErrorMsg, Log.LogEntryType.Error);
                    _success = false; //process has been terminated
                }
                catch (Exception Ex)
                {
                    _jobStatus.ErrorMsg = "Unable to terminate process";
                    _jobLog.WriteEntry(_jobStatus.ErrorMsg + "\r\n" + Ex.Message, Log.LogEntryType.Error);
                    _success = false; //process has been terminated
                }
            }
            else
            {
                _exitCode = Proc.ExitCode; // Store the exit code
                _jobLog.WriteEntry("Process exited with code " + _exitCode.ToString(), Log.LogEntryType.Debug);
            }


            _ExecutionTime = DateTime.Now - ExecutionStartTime;

            //Close out
            try
            {
                Proc.Close();
                Proc.Dispose();
            }
            catch (Exception Ex)
            {
                _jobLog.WriteEntry("Unable to cleanly close process"+ "\r\n" + Ex.Message, Log.LogEntryType.Error);
            }

            Proc = null;

            if (!_jobStatus.Cancelled)
                System.Threading.Thread.Sleep(100);    //Allow for the process to be flush any pending messages
        }
        protected override void InitConfig()
        {
            string folder = Environment.CurrentDirectory.Replace("\\Configs", "") + "\\";
            string file = GetFile("ViewerExe", DEFAULT_CLIENT_EXE, "The executable that runs the viewer.",
                "../../Armadillo-Phoenix/Bin/firestorm-bin.exe",
                "../../Armadillo-Phoenix/Armadillo/Bin/firestorm-bin.exe",
                "C:\\Program Files (x86)\\Firestorm-Release\\Firestorm-Release.exe",
                "C:\\Program Files (x86)\\Firestorm-private-shutle01\\Firestorm-private-shutle01.exe");

            ViewerExecutable = Path.GetFullPath(Path.Combine(folder, file));

            string defaultWD = new Uri(folder).MakeRelativeUri(new Uri(Path.GetDirectoryName(ViewerExecutable))).OriginalString;
            ViewerWorkingDirectory = GetFolder("WorkingDirectory", defaultWD, "The working directory for the viewer executable.");

            Priority = GetEnum<ProcessPriorityClass>("Priority", ProcessPriorityClass.RealTime, "What priority the viewer process should be assigned by the operating system.", LogManager.GetLogger("ViewerConfig"));
            //mViewerArguments = GetGeneralParam("ViewerArguments", "", "Any arguments to be passed to the viewer when it starts.");
            ViewerArguments = GetStr("ViewerArguments", "", "Any arguments to be passed to the viewer when it starts.");
            ViewerToggleHUDKey = GetStr("ViewerToggleHUDKey", "%^{F1}", "The key press that will toggle the HUD on and off in the viewer.");
            UseGrid = Get("UseGrid", false, "Whether to login using the --grid or --loginuri command line parameter to specify the login target.");
            DeltaScale = Get("DeltaScale", .25f, "How much to scale delta values by when using remote control.");
            MasterFrame = GetStr("MasterFrame", "MainWindow", "The name of the frame which is to be the master controller.");
            ViewerNotRespondingTimeoutM = Get("ViewerNotRespondingTimeoutM", 1.0, "How long to wait between update packets before assuming the client has failed and restarting it.");

            GetLocalID = Get("GetLocalID", false, "Whether to check all ObjectUpdate packets until the local ID for the logged in agent is parsed. Required for requesting AvatarPosition and AvatarOrientation.");

            ProxyLoginURI = GetStr("LoginURI", DEFAULT_LOGINURI, "The URI of the server the proxy should proxy.",
                "http://192.168.1.181:9000",
                "http://169.254.189.108:9000",
                "http://138.251.194.191:9000",
                "http://apollo.cs.st-andrews.ac.uk:8002",
                "http://mimuve.cs.st-andrews.ac.uk:8002",
                "http://192.168.1.101:9000",
                "http://localhost:9000 ");

            BlockOnViewerShutdown = Get("BlockOnViewerShutdown", false, "Whether to block while the viewer is being shutdown as the system is shut down. If true the GUI might become unresponsive during shutdown but viewer is more likely to exit correctly.");

            ControlCameraPosition = Get("ControlCameraOffset", false, "Whether to use SetFollowCamProperties packets to control the camera position.");
            AllowFly = Get("AllowFly", false, "Whether to allow the avatar to fly in delta mode.");

            CheckForPause = Get("CheckForPause", false, "Whether the proxy controller should check to see whether the updates have been received which correspond to the updates sent out.");

            UseThread = Get("UseThread", false, "If true then each proxy will spawn a thread to deliver camera updates to the viewer at a constant rate. If false packets will be injected whenever CameraUpdate events are triggered.");
            StartStagger = Get("StartStagger", 60, "How many seconds to way between starting each viewer if multiple viewers are being launched.");
            BackwardsCompatible = Get("BackwardsCompatible", false, "If true, no unusual packets will be injected into the viewer. This will disable remote control and frustum control.");

            CrashLogFile = GetFile("CrashLogFile", "CrashLog.log", "The log file to record crashes to.");
            AutoRestartViewer = Get("AutoRestart", false, "Whether to automatically restart the viewer if the process exits.");
            StartupKeyPresses = GetStr("StartupKeyPresses", "", "A series of key presses, using SendKeys syntax, which will be pressed when the viewer logs in. Separate sequences with commas.");

            LoginFirstName = GetFrame("FirstName", null, "The first name to log the viewer in with.");
            LoginLastName = GetFrame("LastName", null, "The last name to log the viewer in with.");
            LoginPassword = GetFrame("Password", null, "The password to log the viewer in with.");
            ProxyPort = GetFrame("ProxyPort", CURRENT_PORT++, "The port to run the proxy on.");
            LoginGrid = GetFrame("ProxyGrid", "Proxy:" + ProxyPort.ToString(), "The name of the grid the proxy will appear as.");
            AutoLoginClient = LoginFirstName != null && LoginLastName != null && LoginPassword != null;

            AutoStartProxy = GetFrame("AutoStartProxy", false, "Whether to automatically start the proxy when the system start.");
            AutoStartViewer = GetFrame("AutoStartViewer", false, "Whether to automatically start the viewer when the system starts.");
            ControlCamera = GetFrame("ControlCamera", true, "Whether to control the position of the camera on the viewer.");
            ControlFrustum = GetFrame("ControlFrustum", true, "Whether to control the viewing frustum on the viewer.");

            Fill = GetFrameEnum<Fill>("Fill", Fill.Windowed, "What mode to set the window to.", LogManager.GetLogger(Frame + "Viewer"));
            Offset = GetVFrame("Offset", Vector3.Zero, "Offset from the raw camera position to apply.");

            //EnableWindowPackets = Init.Get(generalConfig, "EnableWindowPackets", true);
            //UseSetFollowCamPackets = !enableWindowPackets || Get(generalConfig, "UseSetFollowCamPackets", false);
            //ControlCamera = Init.Get(sectionConfig, "ControlCamera", true);

            //Button Presser
            Key = GetSection("KeyPresser", "Key", "^'", "The button to press ever <IntervalS> seconds.");
            IntervalMS = Get("KeyPresser", "IntervalS", .5, "How long (in seconds) between each Button press.") * 1000.0;
            StopM = Get("KeyPresser", "ShutdownM", 1, "How many minutes the key presser should run before stopping.");
            AutoShutdown = Get("KeyPresser", "AutoShutdown", false, "Whether to shut down the viewer when key presses have stopped.");
        }
Beispiel #58
0
 private void SetAndCheckBasePriority(ProcessPriorityClass exPriorityClass, int priority)
 {
     _process.PriorityClass = exPriorityClass;
     _process.Refresh();
     Assert.Equal(priority, _process.BasePriority);
 }
Beispiel #59
0
        /// <summary>
        /// Starts spring game
        /// </summary>
        /// <param name="client">tasclient to get current battle from</param>
        /// <param name="priority">spring process priority</param>
        /// <param name="affinity">spring process cpu affinity</param>
        /// <param name="scriptOverride">if set, overrides generated script with supplied one</param>
        /// <param name="userName">lobby user name - used to submit score</param>
        /// <param name="passwordHash">lobby password hash - used to submit score</param>
        /// <returns>generates script</returns>
        public string StartGame(TasClient client, ProcessPriorityClass? priority, int? affinity, string scriptOverride, bool useSafeMode = false, bool useMultithreaded=false, BattleContext contextOverride = null, Battle battleOverride = null) {
            if (!File.Exists(paths.Executable) && !File.Exists(paths.DedicatedServer)) throw new ApplicationException(string.Format("Spring or dedicated server executable not found: {0}, {1}", paths.Executable, paths.DedicatedServer));

            this.client = client;
            wasKilled = false;

            if (!IsRunning) {
                gameEndedOk = false;
                IsBattleOver = false;
                lobbyUserName = client.UserName;
                lobbyPassword = client.UserPassword;
                battleResult = new BattleResult();

                talker = new Talker();
                talker.SpringEvent += talker_SpringEvent;
                var battle = battleOverride ?? client.MyBattle;
                isHosting = client != null && battle != null && battle.Founder.Name == client.MyUser.Name;

                if (isHosting) scriptPath = Utils.MakePath(paths.WritableDirectory, "script_" + battle.Founder + ".txt").Replace('\\', '/');
                else scriptPath = Utils.MakePath(paths.WritableDirectory, "script.txt").Replace('\\', '/');

                statsPlayers.Clear();
                statsData.Clear();
                StartContext = null;

                string script;
                if (!string.IsNullOrEmpty(scriptOverride)) {
                    battleResult.IsMission = true;
                    isHosting = false;
                    script = scriptOverride;
                }
                else {
                    List<UserBattleStatus> players;
                    battleGuid = Guid.NewGuid();
                    var service = GlobalConst.GetSpringieService();
                    SpringBattleStartSetup startSetup = null;
                    if (isHosting && GlobalConst.IsZkMod(battle.ModName)) {
                        try {
                            StartContext = contextOverride ?? battle.GetContext();
                            startSetup = service.GetSpringBattleStartSetup(StartContext);
                            if (startSetup.BalanceTeamsResult != null)
                            {
                                StartContext.Players = startSetup.BalanceTeamsResult.Players;
                                StartContext.Bots = startSetup.BalanceTeamsResult.Bots;
                            }
                            connectedPlayers.Clear();
                            foreach (var p in StartContext.Players)
                            {
                                p.IsIngame = true;
                            }
                        } catch (Exception ex) {
                            Trace.TraceError("Error getting start setup: {0}", ex);
                        }
                    }

                    script = battle.GenerateScript(out players, client.MyUser, talker.LoopbackPort, battleGuid.ToString(), startSetup);
                    battleResult.IsMission = battle.IsMission;
                    battleResult.IsBots = battle.Bots.Any();
                    battleResult.Title = battle.Title;
                    battleResult.Mod = battle.ModName;
                    battleResult.Map = battle.MapName;
                    battleResult.EngineVersion = paths.SpringVersion;
                    talker.SetPlayers(players);
                    statsPlayers = players.ToDictionary(x => x.Name,
                                                        x => new BattlePlayerResult
                                                                 {
                                                                     LobbyID = x.LobbyUser.AccountID,
                                                                     AllyNumber = x.AllyNumber,
                                                                     CommanderType = null,
                                                                     // todo commandertype
                                                                     IsSpectator = x.IsSpectator,
                                                                     IsVictoryTeam = false,
                                                                 });
                }
                if (isHosting) timer.Start();

                File.WriteAllText(scriptPath, script);

                LogLines = new StringBuilder();

                var optirun = Environment.GetEnvironmentVariable("OPTIRUN");

                process = new Process();
                process.StartInfo.CreateNoWindow = true;
                List<string> arg = new List<string>();


                if (string.IsNullOrEmpty(optirun))
                {
                    if (UseDedicatedServer)
                    {
                        process.StartInfo.FileName = paths.DedicatedServer;
                        process.StartInfo.WorkingDirectory = Path.GetDirectoryName(paths.DedicatedServer);
                    }
                    else
                    {
                        process.StartInfo.FileName = useMultithreaded ? paths.MtExecutable : paths.Executable;
                        process.StartInfo.WorkingDirectory = Path.GetDirectoryName(paths.Executable);
                    }
                }
                else
                {
                    Trace.TraceInformation("Using optirun {0} to start the game (OPTIRUN env var defined)", optirun);
                    process.StartInfo.FileName = optirun;
                    arg.Add(string.Format("\"{0}\"", (useMultithreaded ? paths.MtExecutable : paths.Executable)));
                }

                

                arg.Add(string.Format("--config \"{0}\"", paths.GetSpringConfigPath()));
                if (useSafeMode) arg.Add("--safemode");
                arg.Add(string.Format("\"{0}\"", scriptPath));
                //Trace.TraceInformation("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);

                process.StartInfo.Arguments = string.Join(" ", arg);
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError = true;
                process.Exited += springProcess_Exited;
                process.ErrorDataReceived += process_ErrorDataReceived;
                process.OutputDataReceived += process_OutputDataReceived;
                process.EnableRaisingEvents = true;

                gamePrivateMessages = new Dictionary<string, int>();
                battleResult.StartTime = DateTime.UtcNow;
                process.Start();
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                if (IsRunning && SpringStarted != null) SpringStarted(this, EventArgs.Empty);

                Utils.StartAsync(() =>
                    {
                        Thread.Sleep(1000);
                        try {
                            if (priority != null) process.PriorityClass = priority.Value;
                            if (affinity != null) process.ProcessorAffinity = (IntPtr)affinity.Value;
                        } catch (Exception ex) {
                            Trace.TraceWarning("Error setting spring process affinity: {0}", ex);
                        }
                    });

                return script;
            }
            else Trace.TraceError("Spring already running");
            return null;
        }
Beispiel #60
-1
 /// <summary>
 /// Executes the <paramref name="executable"/> and waits a maximum time of <paramref name="maxWaitMs"/> for completion. 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="priorityClass">Process priority</param>
 /// <param name="maxWaitMs">Maximum time to wait for completion</param>
 /// <returns><c>true</c> if process was executed and finished correctly</returns>
 public static bool TryExecute(string executable, string arguments, ProcessPriorityClass priorityClass = ProcessPriorityClass.Normal, int maxWaitMs = 1000)
 {
   using (System.Diagnostics.Process process = new System.Diagnostics.Process { StartInfo = new ProcessStartInfo(executable, arguments) { UseShellExecute = false, CreateNoWindow = true } })
   {
     process.Start();
     process.PriorityClass = priorityClass;
     if (process.WaitForExit(maxWaitMs))
       return process.ExitCode == 0;
     if (!process.HasExited)
       process.Kill();
   }
   return false;
 }