Check if process is running on windows/linux

后端 未结 7 2163
一生所求
一生所求 2020-12-10 15:30

i have a process

Runtime rt = Runtime.getRuntime() ;
Process p = rt.exec(filebase+port+\"/hlds.exe +ip \"+ip+\" +maxplayers \"+players+ \" -game cstrike -co         


        
7条回答
  •  南笙
    南笙 (楼主)
    2020-12-10 15:56

    public class ProcessEndNotifier extends Thread
    {
        Process process;
        MyClass classThatNeedsToBeNotified;
    
        public ProcessEndNotifier(MyClass classThatNeedsToBeNotified, Process process)
        {
            this.process = process;
            this.classThatNeedsToBeNotified = classThatNeedsToBeNotified;
        }
    
        @Override
        public void run()
        {
            try {
                process.waitFor();
            }
            catch (InterruptedException e) {
                classThatNeedsToBeNotified.processEnded();
            }
            classThatNeedsToBeNotified.processEnded();
        }
    }
    

    Now you can know if a process in running like this:

    public class MyClass
    {
        boolean isProcessRunning;       
    
        public static void main(String[]args)
        {
            Process process = Runtime.getRuntime().exec("foo -bar");
            isProcessRunning = true;
            new ProcessEndNotifier(this, process).run();
        }
    
        public void processEnded()
        {
            isProcessRunning = false;
            // Or just do stuff here!
        }
    }
    

提交回复
热议问题