繁体   English   中英

从C#控制台应用程序杀死Java进程

[英]Killing Java Process from C# Console App

我不想再发表此文章,但我回答了我自己的最后一篇文章,以为我已解决(我没有)。 基本上,当我的c#.NET应用程序关闭时,我想删除它创建的正在运行的Java进程。 最初的问题是我试图将processID保存到静态的类成员变量(显然不起作用)。 我在线找到了一个Global Class示例,并使用了它,但是它仍然没有关闭该过程。

调试它无法正常工作。 我猜它只是创建应用程序的一个新实例,而不是运行我构建的实例,甚至将工作目录设置为“ Bin”目录也不起作用。 因此,我现在只需要从Bin目录运行.exe。

namespace MinecraftDaemon
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Starting Minecraft Daemon...");

            Arguments CommandLine = new Arguments(args);

            // Hook ProcessExit Event
            AppDomain.CurrentDomain.ProcessExit += new EventHandler(Current_ProcessExit);

            if (CommandLine["file"] != null && CommandLine["memory"] != null)
            {
                // Launch the Application (Command Line Parameters)
                LaunchMinecraft(CommandLine["file"], CommandLine["memory"]);
            }
            else
            {
                // Launch the Application (Default Parameters)
                LaunchMinecraft("minecraft_server.jar", "1024");
            }
        }

        public static void LaunchMinecraft(String file, String memoryValue)
        {
            String memParams = "-Xmx" + memoryValue + "M" + " -Xms" + memoryValue + "M ";
            String args = memParams + "-jar " + file + " nogui";
            ProcessStartInfo processInfo = new ProcessStartInfo("java.exe", args);
            processInfo.CreateNoWindow = true;
            processInfo.UseShellExecute = false;

            try
            {
                using (Process minecraftProcess = Process.Start(processInfo))
                {
                    GlobalClass.ProcessID = minecraftProcess.Id;
                    Console.WriteLine("Process ID is " + GlobalClass.ProcessID);
                    minecraftProcess.WaitForExit();
                }
            }
            catch
            {
                // Log Error
            }
        }

        static void Current_ProcessExit(object sender, EventArgs e)
        {
            // Loop the Current Windows Processes
            foreach (Process winProcess in Process.GetProcesses())
            {
                Console.WriteLine("WinProcessID is " + winProcess.Id + " GlobalClass.ProcessID is " + GlobalClass.ProcessID);

                // If this is our Process, shut it down
                if (winProcess.Id == GlobalClass.ProcessID)
                {
                    Process.GetProcessById(GlobalClass.ProcessID).Kill();
                }
            }
        }
    }
}

通过从捕获事件AppDomain.CurrentDomain.ProcessExit切换为使用SetConsoleCtrlHandler()来解决此问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM