public static Process GetProcessUsingPort(int localPort)
        {
            var connections = IPHlpApi32Wrapper.GetAllTcpConnections();
            var entry       = connections.FirstOrDefault(x => x.LocalPort == localPort);
            var process     = Process.GetProcessById(entry.owningPid);

            return(process);
        }
Exemple #2
0
        public void StartOrFindProcess()
        {
            if (!CanReachServer())
            {
                if (string.IsNullOrEmpty(ExecutablePath) || !File.Exists(ExecutablePath))
                {
                    throw new Exception(string.Format("Redis server not started and executable {0} not found", ExecutablePath));
                }

                ServerProcess           = new Process();
                ServerProcess.StartInfo = new ProcessStartInfo(ExecutablePath)
                {
                    CreateNoWindow         = true,
                    RedirectStandardOutput = true,
                    UseShellExecute        = false,
                };
                ServerProcess.EnableRaisingEvents = true;

                ServerProcess.Start();
                ServerProcess.BeginOutputReadLine();

                logger.Info("Starting {0}...", Path.GetFileName(ExecutablePath));

                // wait enough time
                if (!CanReachServer(5000))
                {
                    throw new Exception(string.Format("Redis Server hasn't been launch correctly (Timeout:{0})", 5000));
                }

                logger.Info("{0} started...", Path.GetFileName(ExecutablePath));
            }
            else
            {
                var processes = Process.GetProcessesByName("redis-server");

                if (processes.Length == 1)
                {
                    ServerProcess = processes[0];
                }
                else if (processes.Length <= 0)
                {
                    throw new Exception("Process redis-server not found");
                }
                else
                {
                    var client      = new RedisClient("localhost");
                    var connections = IPHlpApi32Wrapper.GetAllTcpConnections();
                    var matching    = connections.SingleOrDefault(x => x.LocalPort == ((IPEndPoint)client.Socket.LocalEndPoint).Port);

                    if (matching.Equals(default(MIB_TCPROW_OWNER_PID)))
                    {
                        throw new Exception("Process redis-server not found");
                    }

                    ServerProcess = Process.GetProcessById(matching.owningPid);
                }


                logger.Info("Redis process found (pid:{0})", ServerProcess.Id);
            }
        }