static internal IConfigMapPath GetInstance()
        {
            // IIS 7 bits on <= IIS 6.x: use the metabase
            if (ServerConfig.UseMetabase)
            {
                return((IConfigMapPath)MetabaseServerConfig.GetInstance());
            }

            if (ServerConfig.IISExpressVersion != null)
            {
                return((IConfigMapPath)ServerConfig.GetInstance());
            }

            ProcessHost host = ProcessHost.DefaultHost;
            IProcessHostSupportFunctions functions = null;

            if (null != host)
            {
                functions = host.SupportFunctions;
            }

            if (functions == null)
            {
                functions = HostingEnvironment.SupportFunctions;
            }

            return(new ProcessHostMapPath(functions));
        }
        public void process_is_killed_when_process_host_is_disposed()
        {
            uint processId;

            using (var subject = new ProcessHost("./ExampleInteractiveProcess.exe", Directory.GetCurrentDirectory()))
            {
                subject.Start();
                processId = subject.ProcessId();
            }
            Thread.Sleep(500);
            try
            {
                // system.diagnostics.process throws in debug mode, returns null in release mode!
                var prc = Process.GetProcessById((int)processId);
                Assert.That(prc, Is.Null);
            }
            catch (ArgumentException)
            {
                Assert.Pass();
            }
            catch (InvalidOperationException)
            {
                Assert.Pass();
            }
            Assert.Fail();
        }
    public static int Main(string[] args)
    {
        try {
            Hashtable props = new Hashtable ();
            props ["port"] = 0;
            props ["name"] = "__internal_tcp";
            ChannelServices.RegisterChannel (new TcpChannel (props, null, null));

            string sref = Console.In.ReadLine ();
            byte[] data = Convert.FromBase64String (sref);
            MemoryStream ms = new MemoryStream (data);
            BinaryFormatter bf = new BinaryFormatter ();
            IProcessHostController pc = (IProcessHostController) bf.Deserialize (ms);

            ProcessHost rp = new ProcessHost (pc);
            pc.RegisterHost (rp);
            try {
                pc.WaitForExit ();
            } catch {
            }
            rp.Dispose ();

        } catch (Exception ex) {
        }

        return 0;
    }
 public static void Register(ProcessHost host, string sessionId)
 {
     lock (s_registered)
     {
         s_registered[sessionId] = new WeakReference <ProcessHost>(host);
         if (Port == -1)
         {
             var tcpListener = new TcpListener(IPAddress.Loopback, 0);
             tcpListener.Start();
             Port = ((IPEndPoint)tcpListener.LocalEndpoint).Port;
             tcpListener.Stop();
             new BsonTcpTransport().Listen(IPAddress.Loopback, Port, conn =>
             {
                 conn.OnMessage += (_, msg) =>
                 {
                     if (msg is StartDesignerSessionMessage start)
                     {
                         lock (s_registered)
                         {
                             if (s_registered.TryGetValue(start.SessionId, out var hostref) &&
                                 hostref.TryGetTarget(out var found))
                             {
                                 found.OnSessionStarted(conn);
                             }
                             else
                             {
                                 conn.Dispose();
                             }
                         }
                     }
	public static int Main (string[] args)
	{
		string tmpFile = null;
		TextReader input = null;
		try {
			// The first parameter is the task id
			// The second parameter is the temp file that contains the data
			// If not provided, data is read from the standard input
			
			if (args.Length > 1) {
				tmpFile = args [1];
				input = new StreamReader (tmpFile);
			} else
				input = Console.In;
			
			string sref = input.ReadLine ();
			string pidToWatch = input.ReadLine ();
			
			if (tmpFile != null) {
				try {
					input.Close ();
					File.Delete (tmpFile);
				} catch {
				}
			}
			
			WatchParentProcess (int.Parse (pidToWatch));
			
			string unixPath = RegisterRemotingChannel ();
			
			byte[] data = Convert.FromBase64String (sref);
			MemoryStream ms = new MemoryStream (data);
			BinaryFormatter bf = new BinaryFormatter ();
			IProcessHostController pc = (IProcessHostController) bf.Deserialize (ms);
			
			LoggingService.AddLogger (new LocalLogger (pc.GetLogger (), args[0]));
			
			ProcessHost rp = new ProcessHost (pc);
			pc.RegisterHost (rp);
			try {
				pc.WaitForExit ();
			} catch {
			}
			
			try {
				rp.Dispose ();
			} catch {
			}
			
			if (unixPath != null)
				File.Delete (unixPath);
			
		} catch (Exception ex) {
			Console.WriteLine (ex);
		}
		
		return 0;
	}
Exemple #6
0
 public void can_start_process_as_child()
 {
     using (var subject = new ProcessHost("./ExampleNoninteractiveProcess.exe", Directory.GetCurrentDirectory()))
     {
         subject.StartAsChild("print hello world");
         Thread.Sleep(500);
         var output = subject.StdOut.ReadAllText(Encoding.Default);
         //var output = subject.StdOut.ReadToTimeout(Encoding.Default, TimeSpan.FromSeconds(10));
         Assert.That(output, Is.StringStarting("hello world"));
     }
 }
        public void can_pass_arguments_to_process()
        {
            using (var subject = new ProcessHost("./ExampleNoninteractiveProcess.exe", Directory.GetCurrentDirectory()))
            {
                subject.Start("print hello world");
                Thread.Sleep(250);

                var output = subject.StdOut.ReadAllText(Encoding.Default);
                Assert.That(output, Is.StringStarting("hello world"));
            }
        }
Exemple #8
0
        private ProcessResult RunScript(Script script, string parameterPath, string resultPath)
        {
            string args = $"{SettingsProvider.ScriptDirectoryPath}{script.Name}";

            args += " " + parameterPath;
            args += " " + resultPath;

            args += script.GetParametersAsArgs();

            return(ProcessHost.RunProcess(args));
        }
Exemple #9
0
		static int Main(string[] args)
		{
            if (args.Length > 0 && args[0] == "wait")
            {
                for(;;)
                {
	                Thread.Sleep(1000);
                }
            }

            if (args.Length > 0 && args[0] == "print")
            {
	            Console.WriteLine(string.Join(" ", args.Skip(1)));
                return 0;
            }

            if (args.Length > 0 && args[0] == "envarg")
            {
                var envargs = Environment.GetEnvironmentVariables();
                foreach (DictionaryEntry envarg in envargs)
                {
                    Console.WriteLine(envarg.Key + " = " + envarg.Value);
                }
                return 0;
            }

		    if (args.Length > 0 && args[0] == "spawn")
		    {
                // spawn a new process, and output its ID. Then wait forever
		        var ph = new ProcessHost("ExampleNoninteractiveProcess.exe", "");
                ph.StartAsChild("wait");
		        Console.WriteLine(ph.ProcessId());
		        for(;;)
		        {
		            Thread.Sleep(1000);
		        }
		    }

            
            if (args.Length > 1 && args[0] == "return")
            {
                return int.Parse(args[1]);
            }

			Console.WriteLine(StdOutMsg);
            using (var stdErr = Console.OpenStandardError())
            {
                var msgBytes = Encoding.ASCII.GetBytes(StdErrMsg);
                stdErr.Write(msgBytes, 0, msgBytes.Length);
            }

            return 0;
		}
        public void stress_test()
        {
            for (int i = 0; i < 10000; i++)
            {
                using (var subject = new ProcessHost("./ExampleNoninteractiveProcess.exe", Directory.GetCurrentDirectory()))
                {
                    subject.Start();
                }
            }

            Assert.Pass();
        }
        public void can_get_exit_code_from_process()
        {
            using (var subject = new ProcessHost("./ExampleNoninteractiveProcess.exe", Directory.GetCurrentDirectory()))
            {
                subject.Start("return 1729");

                Assert.That(subject.WaitForExit(one_second), "process did not exit");
                var code = subject.ExitCode();

                Assert.That(code, Is.EqualTo(1729));
            }
        }
        public AvaloniaDesigner(DesignerConfiguration config)
        {
            _host = new ProcessHost(config);
            _host.SpawnedProcess += proc => SpawnedProcess?.Invoke(proc);
            InitializeComponent();
            BindingOperations.SetBinding(State, TextBox.TextProperty,
                                         new Binding(nameof(ProcessHost.State))
            {
                Source = _host, Mode = BindingMode.OneWay
            });

            _host.PropertyChanged   += _host_PropertyChanged;
            DesignerView.DataContext = new HostedAppModel(_host);
        }
        public void can_write_strings_from_a_processes_pipes()
        {
            using (var subject = new ProcessHost("./ExampleInteractiveProcess.exe", Directory.GetCurrentDirectory()))
            {
                subject.Start();

                subject.StdIn.WriteAllText(Encoding.Default, "bye\r\n");

                int exitCode;
                var ok = subject.WaitForExit(one_second, out exitCode);

                Assert.That(ok, Is.True);
                Assert.That(exitCode, Is.EqualTo(0));
            }
        }
        public void can_call_environment_executables()
        {
            using (var subject = new ProcessHost("net", null))
            {
                subject.Start();
                Thread.Sleep(250);

                Assert.That(subject.IsAlive(), Is.False);

                var output = subject.StdOut.ReadAllText(Encoding.Default);
                Assert.That(output, Is.EqualTo(""), "Standard Out");

                var err = subject.StdErr.ReadAllText(Encoding.Default);
                Assert.That(err, Is.StringStarting("The syntax of this command is:"), "Standard Error");
            }
        }
Exemple #15
0
        public void can_pass_environment_variables_to_process()
        {
            using (var subject = new ProcessHost("./ExampleNoninteractiveProcess.exe", Directory.GetCurrentDirectory()))
            {
                var envars = new Dictionary <string, string> {
                    { "one", "two" },
                    { "three", "four" }
                };
                subject.Start("envarg", envars);
                Thread.Sleep(500);

                var output = subject.StdOut.ReadAllWithTimeout(Encoding.Default, TimeSpan.FromSeconds(10));
                Assert.That(output, Is.StringContaining("one = two"));
                Assert.That(output, Is.StringContaining("three = four"));
            }
        }
        public void can_run_and_read_from_a_non_interactive_process()
        {
            using (var subject = new ProcessHost("./ExampleNoninteractiveProcess.exe", Directory.GetCurrentDirectory()))
            {
                subject.Start();
                Thread.Sleep(250);

                Assert.That(subject.IsAlive(), Is.False);

                var output = subject.StdOut.ReadAllText(Encoding.Default);
                Assert.That(output, Is.StringStarting(ExampleNoninteractiveProcess.Program.StdOutMsg), "Standard Out");

                var err = subject.StdErr.ReadAllText(Encoding.Default);
                Assert.That(err, Is.StringStarting(ExampleNoninteractiveProcess.Program.StdErrMsg), "Standard Error");
            }
        }
        public void Writing_to_an_OUT_pipe_throws_an_exception()
        {
            using (var subject = new ProcessHost("./ExampleNoninteractiveProcess.exe", Directory.GetCurrentDirectory()))
            {
                subject.Start();

                var dummy = new byte[2];

                Assert.Throws <Exception>(() => subject.StdOut.Write(dummy, 0, 1));

                int exitCode;
                var exited = subject.WaitForExit(one_second, out exitCode);

                Assert.That(exited, Is.True);
                Assert.That(exitCode, Is.EqualTo(0));
            }
        }
        public void can_impersonate_another_user(string domain, string user, string password)
        {
            var expected = domain + "\\" + user + "\r\n";

            using (var subject = new ProcessHost("whoami", null))
            {
                subject.StartAsAnotherUser(domain, user, password, "");
                subject.WaitForExit(TimeSpan.FromSeconds(2));
                Assert.That(subject.IsAlive(), Is.False);

                var output = subject.StdOut.ReadAllText(Encoding.Default);
                Assert.That(output.ToLower(), Is.EqualTo(expected.ToLower()), "Standard Out");

                var err = subject.StdErr.ReadAllText(Encoding.Default);
                Assert.That(err, Is.Empty, "Standard Error");
            }
        }
        public void can_read_and_write_single_lines_on_a_processes_pipes()
        {
            using (var subject = new ProcessHost("./ExampleInteractiveProcess.exe", Directory.GetCurrentDirectory()))
            {
                subject.Start();

                var read = subject.StdOut.ReadLine(Encoding.Default, one_second);
                Assert.That(read, Is.EqualTo(ExampleProcess.Program.Intro));

                subject.StdIn.WriteLine(Encoding.Default, "bye");

                int exitCode;
                var ok = subject.WaitForExit(one_second, out exitCode);

                Assert.That(ok, Is.True);
                Assert.That(exitCode, Is.EqualTo(0));
            }
        }
        public void can_wait_for_process_and_kill_if_required()
        {
            using (var subject = new ProcessHost("./ExampleNoninteractiveProcess.exe", Directory.GetCurrentDirectory()))
            {
                subject.Start("wait");

                var ended = subject.WaitForExit(one_second);

                Assert.That(ended, Is.False, "Ended");
                Assert.That(subject.IsAlive(), Is.True, "Alive");

                subject.Kill();
                var endedAfterKill = subject.WaitForExit(one_second);

                Assert.That(endedAfterKill, Is.True, "ended after kill");
                Assert.That(subject.IsAlive(), Is.False, "Alive after kill");
                Assert.That(subject.ExitCode(), Is.EqualTo(127), "standard killed code");
            }
        }
Exemple #21
0
        public void child_process_can_be_killed_when_parent_is_killed()
        {
            Process p;
            int     pid;

            using (var subject = new ProcessHost("./ExampleNoninteractiveProcess.exe", Directory.GetCurrentDirectory()))
            {
                // start a process, which calls `StartAsChild`. Then kill that process and check the child died
                subject.Start("spawn");
                var output = subject.StdOut.ReadToTimeout(Encoding.Default, TimeSpan.FromSeconds(1));
                var ok     = int.TryParse(output, out pid);
                Assert.That(ok, Is.True, "PID was {" + output + "}");

                p = Process.GetProcessById(pid);
                Assert.That(p.HasExited, Is.False, "Child process not running");
            }
            Thread.Sleep(500);

            Assert.That(p.HasExited, Is.True, "Child process is still running (pid = " + pid + ")");
        }
        public void can_get_process_id_and_use_with_existing_dotnet_libraries()
        {
            using (var subject = new ProcessHost("./ExampleInteractiveProcess.exe", Directory.GetCurrentDirectory()))
            {
                subject.Start();

                uint id = subject.ProcessId();

                var process = Process.GetProcessById((int)id);
                Assert.That(process.HasExited, Is.False, "Exited");

                process.Kill();

                int exitCode;
                var exited = subject.WaitForExit(one_second, out exitCode);

                Assert.That(exited, Is.True, "Exited after kill");
                Assert.That(exitCode, Is.EqualTo(0), "Exit code");
            }
        }
        internal static IConfigMapPath GetInstance()
        {
            if (ServerConfig.UseMetabase)
            {
                return((IConfigMapPath)MetabaseServerConfig.GetInstance());
            }
            if (ServerConfig.IISExpressVersion != null)
            {
                return((IConfigMapPath)ServerConfig.GetInstance());
            }
            ProcessHost defaultHost = ProcessHost.DefaultHost;
            IProcessHostSupportFunctions supportFunctions = null;

            if (defaultHost != null)
            {
                supportFunctions = defaultHost.SupportFunctions;
            }
            if (supportFunctions == null)
            {
                supportFunctions = HostingEnvironment.SupportFunctions;
            }
            return(new ProcessHostMapPath(supportFunctions));
        }
Exemple #24
0
    public static int Main(string[] args)
    {
        string     tmpFile = null;
        TextReader input   = null;

        try {
            // The first parameter is the task id
            // The second parameter is the temp file that contains the data
            // If not provided, data is read from the standard input

            if (args.Length > 1)
            {
                tmpFile = args [1];
                input   = new StreamReader(tmpFile);
            }
            else
            {
                input = Console.In;
            }

            string sref       = input.ReadLine();
            string pidToWatch = input.ReadLine();

            if (tmpFile != null)
            {
                try {
                    input.Close();
                    File.Delete(tmpFile);
                } catch {
                }
            }

            WatchParentProcess(int.Parse(pidToWatch));

            string unixPath = RegisterRemotingChannel();

            byte[]                 data = Convert.FromBase64String(sref);
            MemoryStream           ms   = new MemoryStream(data);
            BinaryFormatter        bf   = new BinaryFormatter();
            IProcessHostController pc   = (IProcessHostController)bf.Deserialize(ms);

            LoggingService.AddLogger(new LocalLogger(pc.GetLogger(), args[0]));

            ProcessHost rp = new ProcessHost(pc);
            pc.RegisterHost(rp);
            try {
                pc.WaitForExit();
            } catch {
            }

            try {
                rp.Dispose();
            } catch {
            }

            if (unixPath != null)
            {
                File.Delete(unixPath);
            }
        } catch (Exception ex) {
            Console.WriteLine(ex);
        }

        return(0);
    }
        public void Start()
        {
            _stopping = false;
            try
            {
                if (_startArgs.Contains("{0}"))
                {
                    _dummyProcess = Call(Process.GetCurrentProcess().MainModule.FileName, "waitForPid " + Process.GetCurrentProcess().Id);
                    _childProcess = CallAsChildUser(_target, string.Format(_startArgs, _dummyProcess.ProcessId()));
                }
                else
                {
                    _childProcess = CallAsChildUser(_target, _startArgs);
                }

                if (_monitorThread == null || !_monitorThread.IsAlive)
                {
                    _monitorThread = new Thread(() => MonitorChild(_childProcess)) { IsBackground = true };
                    _monitorThread.Start();
                }

                if (_shouldLogOut || _shouldLogErr)
                {
                    var tlogs = new Thread(() => WriteLogs(_childProcess)) {IsBackground = true};
                    tlogs.Start();
                }
            }
            catch (Exception ex)
            {
                WriteWrapperFailure(ex);
            }
        }
        void WriteLogs(ProcessHost childProcess)
        {
            while (!_stopping && IsOk(childProcess))
            {
                var errTxt = childProcess.StdErr.ReadLine(Encoding.UTF8, TimeSpan.FromSeconds(1));
                var outTxt = childProcess.StdOut.ReadLine(Encoding.UTF8, TimeSpan.FromSeconds(1));

                if (string.IsNullOrEmpty(errTxt) && string.IsNullOrEmpty(outTxt))
                {
                    Thread.Sleep(1000);
                    continue;
                }

                if (_shouldLogOut) File.AppendAllText(_stdOutLog, outTxt);
                if (_shouldLogErr) File.AppendAllText(_stdErrLog, errTxt);
            }
        }
 void WaitForExit_ForceKillAfter90Seconds()
 {
     if (!IsOk(_childProcess)) return;
     if (!_childProcess.WaitForExit(TimeSpan.FromSeconds(90)))
     {
         WriteChildFailure("Process did not close gracefully, will be killed");
         _childProcess.Kill();
     }
     _childProcess.Dispose();
     _childProcess = null;
 }
        void MonitorChild(ProcessHost child)
        {
            while (!_stopping && IsOk(child))
            {
                Thread.Sleep(250);
            }
            if (_stopping) return;

            WriteChildFailure("error code: " + _childProcess.ExitCode());
            KillDummy();
            Environment.Exit(_childProcess.ExitCode()); // We die, so the service manager will start us up again.
        }
 void KillDummy()
 {
     if (!IsOk(_dummyProcess)) return;
     _dummyProcess.Kill();
     _dummyProcess.Dispose();
     _dummyProcess = null;
 }
 void ForceKillImmediate()
 {
     if (!IsOk(_childProcess)) return;
     _childProcess.Kill();
     _childProcess.Dispose();
     _childProcess = null;
 }
        ProcessHost CallAsChildUser(string exePath, string args)
        {
            var fullExePath = Path.GetFullPath(exePath);
            var runningDirectory = InitialWorkingDirectory(fullExePath);

            var proc = new ProcessHost(fullExePath, runningDirectory);

            proc.Start(args);

            return proc;
        }
 static bool IsOk(ProcessHost proc)
 {
     return proc != null && proc.IsAlive();
 }
 internal HostedAppModel(ProcessHost host)
 {
     _host           = host;
     Background      = Settings.Background;
     host.OnMessage += OnMessage;
 }
 public void is_compatible_windows()
 {
     Assert.That(ProcessHost.HostIsCompatible(), "Host operating system can't run these tests");
 }