示例#1
0
        private static System.Diagnostics.Process StartWorkerProcess()
        {
            var parentId = System.Diagnostics.Process.GetCurrentProcess().Id;
            var proc     = System.Diagnostics.Process.Start(new ProcessStartInfo
            {
                FileName  = PlatformCompat.Runtime.ExeRunner ?? WorkerExePath,
                Arguments = PlatformCompat.Runtime.ExeRunner != null ? $"{WorkerExePath} {parentId}" : $"{parentId}",
                RedirectStandardOutput = true,
                UseShellExecute        = false
            });

            if (proc == null)
            {
                throw new Exception("Could not start worker process");
            }

            if (PlatformCompat.System.CanUseWin32)
            {
                try
                {
                    var job = new Job();
                    job.AddProcess(proc.Handle);
                }
                catch
                {
                    proc.Kill();
                    throw;
                }
            }

            proc.StandardOutput.Read();

            return(proc);
        }
示例#2
0
        public void Start(Configuration configuration)
        {
            if (_process == null)
            {
                Process[] existingPrivoxy = Process.GetProcessesByName("ss_privoxy");
                foreach (Process p in existingPrivoxy.Where(IsChildProcess))
                {
                    KillProcess(p);
                }
                string privoxyConfig = Resources.privoxy_conf;
                _runningPort  = configuration.httpPort;
                privoxyConfig = privoxyConfig.Replace("__SOCKS_PORT__", configuration.localPort.ToString());
                privoxyConfig = privoxyConfig.Replace("__PRIVOXY_BIND_PORT__", _runningPort.ToString());
                privoxyConfig = privoxyConfig.Replace("__PRIVOXY_BIND_IP__", configuration.shareOverLan ? "0.0.0.0" : "127.0.0.1");
                FileManager.ByteArrayToFile(Utils.GetTempPath(UniqueConfigFile), Encoding.UTF8.GetBytes(privoxyConfig));

                _process = new Process();
                // Configure the process using the StartInfo properties.
                _process.StartInfo.FileName         = "ss_privoxy.exe";
                _process.StartInfo.Arguments        = UniqueConfigFile;
                _process.StartInfo.WorkingDirectory = Utils.GetTempPath();
                _process.StartInfo.WindowStyle      = ProcessWindowStyle.Hidden;
                _process.StartInfo.UseShellExecute  = true;
                _process.StartInfo.CreateNoWindow   = true;
                _process.Start();

                /*
                 * Add this process to job obj associated with this ss process, so that
                 * when ss exit unexpectedly, this process will be forced killed by system.
                 */
                PrivoxyJob.AddProcess(_process.Handle);
            }
            RefreshTrayArea();
        }
示例#3
0
        public void Start()
        {
            if (process == null)
            {
                Process[] existingPrivoxy = Process.GetProcessesByName("ss_privoxy");
                foreach (Process p in existingPrivoxy.Where(IsChildProcess))
                {
                    KillProcess(p);
                }
                process = new Process();
                process.StartInfo.FileName         = "ss_privoxy.exe";
                process.StartInfo.Arguments        = Path.Combine(directory, config_txt);
                process.StartInfo.WorkingDirectory = directory;
                process.StartInfo.WindowStyle      = ProcessWindowStyle.Hidden;
                process.StartInfo.UseShellExecute  = true;
                process.StartInfo.CreateNoWindow   = true;
                process.Start();

                /*
                 * Add this process to job obj associated with this ss process, so that
                 * when ss exit unexpectedly, this process will be forced killed by system.
                 */
                job.AddProcess(process.Handle);
            }
        }
            private PhantomServer()
            {
                _process = new Process
                {
                    StartInfo =
                    {
                        WorkingDirectory       = _phantomJsFolder,
                        FileName               = "\"" + _phantomJsPath + "\"",
                        Arguments              = string.Format("--config={0} {1}", ConfigFileName, ScriptFileName),
                        RedirectStandardOutput = true,
                        RedirectStandardError  = true,
                        RedirectStandardInput  = true,
                        CreateNoWindow         = true,
                        StandardOutputEncoding = Encoding.UTF8,
                        UseShellExecute        = false,
                        WindowStyle            = ProcessWindowStyle.Hidden
                    }
                };

                _process.Start();

                _stdin           = _process.StandardInput;
                _stdout          = _process.StandardOutput;
                _stderror        = _process.StandardError;
                _stdin.AutoFlush = true;

                _job = new Job();
                _job.AddProcess(_process.Handle);
            }
示例#5
0
        protected static void NPMThread()
        {
            Process cmd = new Process();

            cmd.StartInfo.FileName = "cmd.exe";
            cmd.StartInfo.RedirectStandardInput  = true;
            cmd.StartInfo.RedirectStandardOutput = true;
            cmd.StartInfo.RedirectStandardError  = false;
            cmd.StartInfo.WorkingDirectory       = "../../View";
            cmd.StartInfo.CreateNoWindow         = true;
            cmd.StartInfo.UseShellExecute        = false;
            cmd.Start();

            job = new Job();
            job.AddProcess(cmd.Handle);

            cmd.StandardInput.WriteLine("npm run integrated 2>&1");
            cmd.StandardInput.Flush();

            while (true)
            {
                String line = cmd.StandardOutput.ReadLine();
                if (line == null)
                {
                    break;
                }
                Console.WriteLine(line);
                if (line.Contains("Project is running at"))
                {
                    waitForNPM.Set();
                }
            }
        }
示例#6
0
            private PhantomServer()
            {
                var tempDirectory    = PathUtil.Resolve(GlobalSettingsFacade.TempDirectory);
                var cachePath        = Path.Combine(tempDirectory, "phantomjs_cache");
                var localStoragePath = Path.Combine(tempDirectory, "phantomjs_ls");

                _process = new Process
                {
                    StartInfo =
                    {
                        WorkingDirectory       = _phantomJsFolder,
                        FileName               = "\"" + _phantomJsPath + "\"",
                        Arguments              = $"\"--local-storage-path={localStoragePath}\" \"--disk-cache-path={cachePath}\" --config={ConfigFileName} {ScriptFileName}",
                        RedirectStandardOutput = true,
                        RedirectStandardError  = true,
                        RedirectStandardInput  = true,
                        CreateNoWindow         = true,
                        StandardOutputEncoding = Encoding.UTF8,
                        UseShellExecute        = false,
                        WindowStyle            = ProcessWindowStyle.Hidden
                    }
                };

                _process.Start();

                _stdin           = _process.StandardInput;
                _stdout          = _process.StandardOutput;
                _stderror        = _process.StandardError;
                _stdin.AutoFlush = true;

                _job = new Job();
                _job.AddProcess(_process.Handle);
            }
示例#7
0
        private static void Impersonate()
        {
            var exeName          = Process.GetCurrentProcess().MainModule.FileName;
            var args             = $"--appRootPath={_options.AppRootPath} --port={_options.Port}";
            var processStartInfo = new ProcessStartInfo(exeName, args)
            {
                Domain                 = _options.Domain,
                UserName               = _options.UsernameWithoutDomain,
                Password               = _options.Password.ToSecureString(),
                UseShellExecute        = false,
                RedirectStandardError  = true,
                RedirectStandardOutput = true,
                RedirectStandardInput  = true,
                CreateNoWindow         = true,
                Verb = "runas"
            };

            _childProcess = Process.Start(processStartInfo);
            if (_childProcess == null)
            {
                throw new Exception("Impersonation of child process failed");
            }
            _childProcess.BeginOutputReadLine();
            _childProcess.BeginErrorReadLine();
            _childProcess.OutputDataReceived += (sender, eventArgs) => Console.WriteLine(eventArgs.Data);
            _childProcess.ErrorDataReceived  += (sender, eventArgs) => Console.Error.WriteLine(eventArgs.Data);

            var job = new Job();

            job.AddProcess(_childProcess.Handle);
        }
示例#8
0
        public void Start()
        {
            var cmdLine = CmdLine;

            Psi.FileName  = StringsUtils.SeparateText(ref cmdLine, ' ');
            Psi.Arguments = cmdLine;

            Prc = Process.Start(Psi);
            if (Prc != null)
            {
                Prc.EnableRaisingEvents = true;
                Prc.Exited += (sender, e) =>
                {
                    if (Prc != null)
                    {
                        Prc = null;
                        Start();
                    }
                };
                var j   = new Job();
                var res = j.AddProcess(Prc.Handle);
                if (!res)
                {
                    var b = Marshal.GetLastWin32Error();
                    Console.WriteLine($"Error {b}");
                }
            }
        }
示例#9
0
        public bool StartIfNeeded()
        {
            if (_disposed)
            {
                throw new ObjectDisposedException(GetType().FullName);
            }

            lock (_startProcessLock)
            {
                if (_started && !_pluginProcess.HasExited)
                {
                    return(false);
                }

                var localPort = GetNextFreeTcpPort();
                LocalEndPoint = new IPEndPoint(IPAddress.Loopback, localPort);

                _pluginProcess.StartInfo.Environment["SS_LOCAL_HOST"] = LocalEndPoint.Address.ToString();
                _pluginProcess.StartInfo.Environment["SS_LOCAL_PORT"] = LocalEndPoint.Port.ToString();
                _pluginProcess.Start();
                _pluginJob.AddProcess(_pluginProcess.Handle);
                _started = true;
            }

            return(true);
        }
示例#10
0
 private void RemoteClient_AddProcess(object sender, EventArgs e)
 {
     if (remoteClient == null || remoteClient.handler == IntPtr.Zero)
     {
         return;
     }
     job.AddProcess(remoteClient.handler);
 }
示例#11
0
        public MainForm()
        {
            InitializeComponent();

            // Add the current process to the sandbox
            _job.AddProcess(Process.GetCurrentProcess().Handle);
            TimeoutOptionsComboBox.SelectedIndex = 0;
        }
示例#12
0
文件: Program.cs 项目: doterik/Zamp
        static void KillExcelWithWindowsJob()
        {
            DoNotReleaseCOM();
            Job  job = new Job();
            uint pid = 0;

            GetWindowThreadProcessId(new IntPtr(hWnd), out pid);
            job.AddProcess(Process.GetProcessById((int)pid).Handle);
        }
示例#13
0
        static void Main(string[] args)
        {
            using (var job = new Job())
            {
                var prc = ProcessFactory.CreateProcess("../../../JobObject.Test.ChildProcess/bin/Debug/JobObject.Test.ChildProcess.exe", "test", null);

                job.AddProcess(prc);

                Console.Read();
            }
        }
示例#14
0
文件: App.xaml.cs 项目: uxifiit/UXC
        public App()
        {
            // Wrap the current main process in the job, so any other new child process started by this process will be managed by this job.
            // If the main process exits or is killed, the job is closed and all other child processes belonging to this job are closed as well.
            _job = new Job();
            _job.AddProcess(Process.GetCurrentProcess().Id);

            _kernel = CreateKernel();
            _config = _kernel.Get <IAppConfiguration>();

            InitializeComponent();
        }
示例#15
0
        public void Start(int localPort, Config config)
        {
            try
            {
                if (_process == null)
                {
                    Process[] existingPrivoxy = Process.GetProcessesByName("v2ray_privoxy");
                    foreach (Process p in existingPrivoxy.Where(IsChildProcess))
                    {
                        KillProcess(p);
                    }
                    string privoxyConfig = Resources.privoxy_conf;
                    RunningPort   = config.GetLocalPort(Global.InboundHttp);
                    privoxyConfig = privoxyConfig.Replace("__SOCKS_PORT__", localPort.ToString());
                    privoxyConfig = privoxyConfig.Replace("__PRIVOXY_BIND_PORT__", RunningPort.ToString());
                    if (config.allowLANConn)
                    {
                        privoxyConfig = privoxyConfig.Replace("__PRIVOXY_BIND_IP__", "0.0.0.0");
                    }
                    else
                    {
                        privoxyConfig = privoxyConfig.Replace("__PRIVOXY_BIND_IP__", Global.Loopback);
                    }
                    FileManager.ByteArrayToFile(Utils.GetTempPath(_uniqueConfigFile), Encoding.UTF8.GetBytes(privoxyConfig));

                    _process = new Process
                    {
                        // Configure the process using the StartInfo properties.
                        StartInfo =
                        {
                            FileName         = "v2ray_privoxy.exe",
                            Arguments        = _uniqueConfigFile,
                            WorkingDirectory = Utils.GetTempPath(),
                            WindowStyle      = ProcessWindowStyle.Hidden,
                            UseShellExecute  = true,
                            CreateNoWindow   = true
                        }
                    };
                    _process.Start();

                    /*
                     * Add this process to job obj associated with this ss process, so that
                     * when ss exit unexpectedly, this process will be forced killed by system.
                     */
                    _privoxyJob.AddProcess(_process.Handle);
                }
            }
            catch (Exception ex)
            {
                Utils.SaveLog(ex.Message, ex);
            }
        }
示例#16
0
            public void Start()
            {
                AssertAdministratorPrivileges();

                var process = new System.Diagnostics.Process();

                process.StartInfo.UseShellExecute        = false;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.CreateNoWindow         = true;
                process.StartInfo.FileName  = Path.Combine(Helpers.AssemblyDirectory, "..", "..", "..", "Containerizer", "bin", "Containerizer.exe");
                process.StartInfo.Arguments = ExternalIP + " " + Port.ToString();
                Retry.Do(() => process.Start(), TimeSpan.FromSeconds(1), 5);
                job.AddProcess(process.Handle);
                process.StandardOutput.ReadLine().should_start_with("SUCCESS");
            }
示例#17
0
            public void Start()
            {
                AssertAdministratorPrivileges();

                var process = new System.Diagnostics.Process();

                process.StartInfo.UseShellExecute        = false;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.CreateNoWindow         = true;
                process.StartInfo.FileName  = Path.Combine(Helpers.AssemblyDirectory, "..", "..", "..", "Containerizer", "bin", "Containerizer.exe");
                process.StartInfo.Arguments = " --machineIP " + MachineIP + " --port " + Port.ToString() + " --containerDirectory " + ContainerDirectory;
                Retry.Do(() => process.Start(), TimeSpan.FromSeconds(1), 5);
                job.AddProcess(process.Handle);
                process.StandardOutput.ReadLine().should_contain("containerizer.started");
                process.StandardOutput.ReadToEndAsync();
            }
示例#18
0
    /*
     *
     * if I have a job
     * 1) walk to one of the jobs workingnodes
     * 2) add completion to the job
     * 3) if job complete: repeat 0)
     *
     */

    void Update()
    {
        if (Time.time < sleepUntil)
        {
            return;
        }

        if (job == null || job.IsComplete())
        {
            job = JobManager.instance.TryGetJob();
            if (job == null)
            {
                sleepUntil = Time.time + .2f;
                return;
            }
            else
            {
                if (job == previousJob)
                {
                    sleepUntil = Time.time + sleepTimeAfterSameJobAssigned;
                    JobManager.instance.QueueJob(job);
                    job = null;
                    return;
                }
                InstantiateJob instantiateJob = job as InstantiateJob;
                if (instantiateJob != null)
                {
                    PathRequestManager.RequestPath(new PathRequest(
                                                       World.nodes[World.nodeCoordFromWorldPos(transform.position)],
                                                       instantiateJob.building.workerNodes.ToList(),
                                                       OnPathFound));
                }
            }
        }

        InstantiateJob instantiateJob2 = job as InstantiateJob;

        if (instantiateJob2 != null)
        {
            if (instantiateJob2.building.workerNodes.Contains(occupiedNode as PlanetNode))
            {
                job.AddProcess(Time.deltaTime * .3f);
            }
        }
    }
示例#19
0
        public void Start(int socksPort)
        {
            if (_process != null)
            {
                throw new Exception("Alreay started. Please stop it first.");
            }

            //if(_process == null) {
            Process[] existingPrivoxy = Process.GetProcessesByName("ss_privoxy");
            foreach (Process p in existingPrivoxy)
            {
                KillProcess(p);
            }

            StringBuilder privoxyConfig = new StringBuilder(Resources.privoxy_conf);
            int           _runningPort  = NetUtils.GetFreePortFrom(DefaultRunningPort);

            BindEp.Port = _runningPort;

            privoxyConfig.Replace("__SOCKS_PORT__", socksPort.ToString());
            privoxyConfig.Replace("__PRIVOXY_BIND_PORT__", BindPort.ToString());
            //privoxyConfig.Replace("__PRIVOXY_BIND_IP__", config.ShareOverLan ? "0.0.0.0" : "127.0.0.1");
            privoxyConfig.Replace("__PRIVOXY_BIND_IP__", BindIp.ToString());
            File.WriteAllText(Utils.GetTempPath(UniqueConfigFile), privoxyConfig.ToString());


            _process = new Process();
            _process.StartInfo.FileName         = ExeFile;
            _process.StartInfo.Arguments        = UniqueConfigFile;
            _process.StartInfo.WorkingDirectory = Utils.GetTempPath();
            _process.StartInfo.WindowStyle      = ProcessWindowStyle.Hidden;
            _process.StartInfo.UseShellExecute  = true;
            _process.StartInfo.CreateNoWindow   = true;
            _process.Start();


            PrivoxyJob.AddProcess(_process.Handle);

            logger.Info("Start Privoxy on " + BindEp);

            //}
            //RefreshTrayArea();
        }
示例#20
0
 void SetCPULimit()
 {
     if (attachedProcess == null)
     {
         return;
     }
     try
     {
         if (job == null)
         {
             job = Job.Create();
             job.AddProcess(attachedProcess);
         }
         job.SetCpuLimit(CpuLimitPercent);
     }
     catch (Exception ex)
     {
     }
 }
示例#21
0
        public void Start(Configuration configuration)
        {
            if (_process == null)
            {
                Process[] existingPrivoxy = Process.GetProcessesByName(PROCESS_NAME);
                foreach (Process p in existingPrivoxy.Where(IsChildProcess))
                {
                    KillProcess(p);
                }
                string privoxyConfig = Resources.privoxy_conf;
                _runningPort  = GetFreePort();
                privoxyConfig = privoxyConfig.Replace("__SOCKS_PORT__", configuration.localPort.ToString());
                privoxyConfig = privoxyConfig.Replace("__PRIVOXY_BIND_PORT__", _runningPort.ToString());
                var isIPv6Enabled = false;
                privoxyConfig = isIPv6Enabled
                    ? privoxyConfig.Replace("__PRIVOXY_BIND_IP__", configuration.shareOverLan ? "[::]" : "[::1]")
                                .Replace("__SOCKS_HOST__", "[::1]")
                    : privoxyConfig.Replace("__PRIVOXY_BIND_IP__", configuration.shareOverLan ? "0.0.0.0" : "127.0.0.1")
                                .Replace("__SOCKS_HOST__", "127.0.0.1");
                FileManager.ByteArrayToFile(Utils.GetTempPath(_uniqueConfigFile), Encoding.UTF8.GetBytes(privoxyConfig));

                _process = new Process
                {
                    // Configure the process using the StartInfo properties.
                    StartInfo =
                    {
                        FileName         = PROCESS_NAME_WITHEXT,
                        Arguments        = _uniqueConfigFile,
                        WorkingDirectory = Utils.GetTempPath(),
                        WindowStyle      = ProcessWindowStyle.Hidden,
                        UseShellExecute  = true,
                        CreateNoWindow   = true
                    }
                };
                _process.Start();

                /*
                 * Add this process to job obj associated with this ss process, so that
                 * when ss exit unexpectedly, this process will be forced killed by system.
                 */
                _privoxyJob.AddProcess(_process.Handle);
            }
        }
示例#22
0
        private static void Impersonate(string[] args)
        {
            if (args.Length > 0)
            {
                string app_args = string.Empty;
                string exeName  = args[0];

                if (args.Length > 1)
                {
                    app_args = args[1];
                }

                ProcessStartInfo processStartInfo = new ProcessStartInfo(exeName, app_args)
                {
                    Domain                 = _options.Domain,
                    UserName               = _options.UsernameWithoutDomain,
                    Password               = _options.Password.ToSecureString(),
                    UseShellExecute        = false,
                    RedirectStandardError  = true,
                    RedirectStandardOutput = true,
                    RedirectStandardInput  = true,
                    CreateNoWindow         = true,
                    Verb = "runas"
                };
                _childProcess = Process.Start(processStartInfo);
                if (_childProcess == null)
                {
                    throw new Exception("Impersonation of child process failed");
                }
                _childProcess.BeginOutputReadLine();
                _childProcess.BeginErrorReadLine();
                _childProcess.OutputDataReceived += (sender, eventArgs) => Console.WriteLine(eventArgs.Data);
                _childProcess.ErrorDataReceived  += (sender, eventArgs) => Console.Error.WriteLine(eventArgs.Data);

                var job = new Job();
                job.AddProcess(_childProcess.Handle);
            }
            else
            {
                throw new Exception("Missing application executable parameter");
            }
        }
示例#23
0
        public bool StartIfNeeded()
        {
            if (_disposed)
            {
                throw new ObjectDisposedException(GetType().FullName);
            }

            lock (_startProcessLock)
            {
                if (_started && !_pluginProcess.HasExited)
                {
                    return(false);
                }

                var localPort = GetNextFreeTcpPort();
                LocalEndPoint = new IPEndPoint(IPAddress.Loopback, localPort);

                _pluginProcess.StartInfo.Environment["SS_LOCAL_HOST"] = LocalEndPoint.Address.ToString();
                _pluginProcess.StartInfo.Environment["SS_LOCAL_PORT"] = LocalEndPoint.Port.ToString();
                _pluginProcess.StartInfo.Arguments = ExpandEnvironmentVariables(_pluginProcess.StartInfo.Arguments, _pluginProcess.StartInfo.EnvironmentVariables);
                try
                {
                    _pluginProcess.Start();
                }
                catch (System.ComponentModel.Win32Exception ex)
                {
                    // do not use File.Exists(...), it can not handle the scenarios when the plugin file is in system environment path.
                    // https://docs.microsoft.com/en-us/windows/win32/seccrypto/common-hresult-values
                    //if ((uint)ex.ErrorCode == 0x80004005)
                    //  https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-erref/18d8fbe8-a967-4f1c-ae50-99ca8e491d2d
                    if (ex.NativeErrorCode == 0x00000002)
                    {
                        throw new FileNotFoundException(I18N.GetString("Cannot find the plugin program file"), _pluginProcess.StartInfo.FileName, ex);
                    }
                    throw new ApplicationException(I18N.GetString("Plugin Program"), ex);
                }
                _pluginJob.AddProcess(_pluginProcess.Handle);
                _started = true;
            }

            return(true);
        }
        public void Start(Configuration configuration)
        {
            if (_process == null)
            {
                var existingPrivoxy = Process.GetProcessesByName(ExeNameNoExt);
                foreach (var p in existingPrivoxy.Where(IsChildProcess))
                {
                    KillProcess(p);
                }
                var privoxyConfig = Resources.privoxy_conf;
                RunningPort   = GetFreePort();
                privoxyConfig = privoxyConfig.Replace(@"__SOCKS_PORT__", configuration.localPort.ToString());
                privoxyConfig = privoxyConfig.Replace(@"__PRIVOXY_BIND_PORT__", RunningPort.ToString());
                privoxyConfig = privoxyConfig.Replace(@"__PRIVOXY_BIND_IP__",
                                                      configuration.shareOverLan ? Configuration.AnyHost : Configuration.LocalHost)
                                .Replace(@"__SOCKS_HOST__", Configuration.LocalHost);
                FileManager.ByteArrayToFile(Utils.GetTempPath(UNIQUE_CONFIG_FILE), Encoding.UTF8.GetBytes(privoxyConfig));

                _process = new Process
                {
                    // Configure the process using the StartInfo properties.
                    StartInfo =
                    {
                        FileName         = ExeName,
                        Arguments        = UNIQUE_CONFIG_FILE,
                        WorkingDirectory = Utils.GetTempPath(),
                        WindowStyle      = ProcessWindowStyle.Hidden,
                        UseShellExecute  = true,
                        CreateNoWindow   = true
                    }
                };
                _process.Start();

                /*
                 * Add this process to job obj associated with this ss process, so that
                 * when ss exit unexpectedly, this process will be forced killed by system.
                 */
                PRIVOXY_JOB.AddProcess(_process.Handle);
            }
        }
示例#25
0
        public void Start(int localPort)
        {
            if (_process == null)
            {
                Process[] existingPrivoxy = Process.GetProcessesByName("v2ray_privoxy");
                foreach (Process p in existingPrivoxy.Where(IsChildProcess))
                {
                    KillProcess(p);
                }
                string privoxyConfig = Resources.privoxy_conf;
                _runningPort  = GetFreePort(localPort);
                privoxyConfig = privoxyConfig.Replace("__SOCKS_PORT__", localPort.ToString());
                privoxyConfig = privoxyConfig.Replace("__PRIVOXY_BIND_PORT__", _runningPort.ToString());
                privoxyConfig = privoxyConfig.Replace("__PRIVOXY_BIND_IP__", "0.0.0.0");
                FileManager.ByteArrayToFile(Utils.GetTempPath(_uniqueConfigFile), Encoding.UTF8.GetBytes(privoxyConfig));

                _process = new Process
                {
                    // Configure the process using the StartInfo properties.
                    StartInfo =
                    {
                        FileName         = "v2ray_privoxy.exe",
                        Arguments        = _uniqueConfigFile,
                        WorkingDirectory = Utils.GetTempPath(),
                        WindowStyle      = ProcessWindowStyle.Hidden,
                        UseShellExecute  = true,
                        CreateNoWindow   = true
                    }
                };
                _process.Start();

                /*
                 * Add this process to job obj associated with this ss process, so that
                 * when ss exit unexpectedly, this process will be forced killed by system.
                 */
                _privoxyJob.AddProcess(_process.Handle);
                _isRunning = true;
            }
        }
示例#26
0
        public void Start(Configuration configuration)
        {
            if (_process == null)
            {
                var existingPrivoxy = Process.GetProcessesByName(PROCESS_NAME);
                foreach (var p in existingPrivoxy.Where(IsChildProcess))
                {
                    p.KillProcess();
                }
                var privoxyConfig = Resources.privoxy_conf;
                privoxyConfig = privoxyConfig.Replace("__SOCKS_PORT__", configuration.corePort.ToString());
                privoxyConfig = privoxyConfig.Replace("__PRIVOXY_BIND_PORT__", configuration.localPort.ToString());
                var isIPv6Enabled = false;
                privoxyConfig = isIPv6Enabled
                    ? privoxyConfig.Replace("__PRIVOXY_BIND_IP__", configuration.shareOverLan ? "[::]" : "[::1]")
                                .Replace("__SOCKS_HOST__", "[::1]")
                    : privoxyConfig.Replace("__PRIVOXY_BIND_IP__", configuration.shareOverLan ? "0.0.0.0" : "127.0.0.1")
                                .Replace("__SOCKS_HOST__", "127.0.0.1");

                File.WriteAllText(Utils.GetTempPath(_uniqueConfigFile), privoxyConfig);
                _process = new Process
                {
                    StartInfo =
                    {
                        FileName         = PROCESS_NAME_WITHEXT,
                        Arguments        = _uniqueConfigFile,
                        WorkingDirectory = Utils.GetTempPath(),
                        WindowStyle      = ProcessWindowStyle.Hidden,
                        UseShellExecute  = true,
                        CreateNoWindow   = true
                    }
                };
                _process.Start();
                _privoxyJob.AddProcess(_process.Handle);
            }
        }
示例#27
0
 public MainWindow()
 {
     InitializeComponent();
     _job = new Job();
     _job.AddProcess(Process.GetCurrentProcess().Id);
 }
示例#28
0
        public static int Run(string exe, string args, Action <string> newData, string workingDir, bool store, out string result)
        {
            //Logger.Info("Run: " + exe + " " + args);

            result = null;

            var proc = new Process();

            proc.StartInfo.FileName  = exe;
            proc.StartInfo.Arguments = args;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.StartInfo.RedirectStandardError  = true;
            proc.StartInfo.UseShellExecute        = false;
            proc.StartInfo.CreateNoWindow         = true;
            if (workingDir != null)
            {
                proc.StartInfo.WorkingDirectory = workingDir;
            }

            if (true)
            {
                proc.EnableRaisingEvents = true;

                // You can pass any delegate that matches the appropriate
                // signature to ErrorDataReceived and OutputDataReceived
                proc.ErrorDataReceived += (sender, errorLine) =>
                {
                    if (errorLine.Data != null)
                    {
                        newData(errorLine.Data + "\r\n");
                    }
                    if (errorLine.Data == "")
                    {
                        newData("\r\n");
                    }
                };

                proc.OutputDataReceived += (sender, outputLine) =>
                {
                    if (outputLine.Data != null)
                    {
                        //                    proc.StandardOutput.ReadLine()
                        newData(outputLine.Data + "\r\n");//
                        //newData("\r\n");
                    }
                    if (outputLine.Data == "")
                    {
                        newData("\r\n");
                    }
                };
            }



            var j = new Job();

            // Do something here

            proc.Start();
            j.AddProcess(proc.Handle);

            if (true)
            {
                proc.BeginErrorReadLine();
                proc.BeginOutputReadLine();
            }


            if (false)
            {
                bool stopped = false;
                //var li = new List<String>();
                var t = new Thread(() =>
                {
                    while (!stopped)
                    {
                        var l = proc.StandardOutput.ReadLine();
                        if (l == null)
                        {
                            continue;
                        }
                        //li.Add(l);
                        newData(l + "\r\n");

                        if (l == "")
                        {
                            newData("\r\n");
                        }
                    }
                    var remainder = proc.StandardOutput.ReadToEnd();
                    //li.Add(remainder);
                    newData(remainder);
                });
                t.Start();
            }

            proc.WaitForExit();

            var exitCode = proc.ExitCode;

            proc.Close();

            return(exitCode);
        }
示例#29
0
        static void Main(string[] args)
        {
            // outside of try to ensure safely cleaned up
            Process child = null;

            try
            {
                uint   ppid    = 0;                           // the parent process ID
                string working = "";                          // the working directory

                string        exec     = null;                // the executable
                List <string> execArgs = new List <string>(); // the executable args

                bool   screenshots                 = false;
                string screenshotFolder            = null;
                ProcessPriorityClass?priorityClass = null;
                ProcessWindowStyle?  windowStyle   = null;

                ParseArgs(args, ref ppid, ref working, ref exec, ref screenshots, ref screenshotFolder, ref priorityClass, ref windowStyle, execArgs);

                if (screenshots)
                {
                    performScreenshots(screenshotFolder);

                    // and quit silently
                    return;
                }

                // verify args
                if (exec == null)
                {
                    // quit silently
                    return;
                }

                // determine this (self) and parent processes
                Process self = Process.GetCurrentProcess();

                // (for parent, need to use 'OpenProcess' API for waitable handle. Managed Process class does not always provide one.)
                IntPtr parent = ppid > 0 ? OpenProcess(ProcessSecurityAndAccessRights_SYNCHRONIZE, true, (int)ppid) : IntPtr.Zero;

                // establish a job object and add itself
                Job job = new Job();
                job.AddProcess(self.Id);

                // kick off the child process...
                var startInfo = new ProcessStartInfo(exec, string.Join(" ", execArgs))
                {
                    UseShellExecute        = false,
                    RedirectStandardError  = false,
                    RedirectStandardInput  = false,
                    RedirectStandardOutput = false
                };
                // in testing, had had no effect
                if (windowStyle.HasValue)
                {
                    startInfo.WindowStyle = windowStyle.Value;
                }

                child = Process.Start(startInfo);
                if (priorityClass.HasValue)
                {
                    child.PriorityClass = priorityClass.Value;
                }

                var childPID = child.Id;

                // ... and add new process (child) to the job
                job.AddProcess(childPID);

                List <ManualResetEvent> toWaitOn = new List <ManualResetEvent>();

                // wait on the child...
                toWaitOn.Add(IntPtrToManualResetEvent(child.Handle));

                // ... and parent (if specified)
                if (parent != IntPtr.Zero)
                {
                    toWaitOn.Add(IntPtrToManualResetEvent(parent));
                }

                // wait on either
                int signalledElement = WaitHandle.WaitAny(toWaitOn.ToArray());

                if (signalledElement > 0)
                {
                    // the parent stopped (likely unexpectidly)
                    // so kill the child and quickly die
                    child.Kill();
                }

                // wait for child to die (is redundant but no harm)...
                child.WaitForExit();

                // and pick up exit code to actually exit with
                int exitCode = child.ExitCode;
                Environment.Exit(exitCode);
            }
            catch (Exception exc)
            {
                // should never get here but just in case, clean up what you can
                try
                {
                    if (child != null)
                    {
                        child.Kill();
                    }
                }
                catch { }

                // produce a response message (for possible JSON consumption) and quit
                Console.WriteLine("{\"event\": \"LaunchFailure\", \"arg\": \"" + JSONEscape(exc.Message + " (" + exc.GetType() + ")") + "\"}");
                return;
            }
        }
        public void Start()
        {
            var torshify = Process.GetProcessesByName("TRock.Music.Torshify.Server").FirstOrDefault();

            if (torshify == null)
            {
                torshify = StartTorshifyServer();
            }

            if (torshify != null && CloseServerTogetherWithClient)
            {
                _job = new Job();
                _job.AddProcess(torshify.Handle);
            }
        }
示例#31
-1
        public void Start(Configuration configuration)
        {
            if (_process != null)
            {
                return;
            }
            KillAll();
            var config = Utils.GetTempPath(_uniqueConfigFile);

            File.WriteAllText(config, V2Ray.GenerateVNextConf(configuration.GetCurrentServer(), configuration.corePort, configuration.shareOverLan ? "0.0.0.0" : "127.0.0.1"));
            _process = new Process
            {
                StartInfo =
                {
                    FileName         = V2Ray.V2RAY_CORE,
                    Arguments        = $"-config {config}",
                    WorkingDirectory = Global.AppPath,
                    WindowStyle      = ProcessWindowStyle.Hidden,
                    UseShellExecute  = true,
                    CreateNoWindow   = true
                }
            };
            _process.Start();
            _v2rayJob.AddProcess(_process.Handle);
        }