-1

I Have two java programs : Demo1.java and Demo2.java

Demo2.java

public class Demo2 extends Thread{
  public void run(){
    while(true){
     System.out.println("Demo2 is running");
    }
  }
}

I want to :

  1. Run Demo2
  2. While Demo2 is running run Demo1
  3. Find out from Demo1 if Demo2 is running.

How should I write Demo1.java?

Abhishek Roy
  • 63
  • 1
  • 3
  • 10
  • 1
    Are they run seperately or is each thread ``start()``ed from the same ``main(String[])``? – f1sh May 30 '18 at 08:49
  • [You want thread communication](https://www.tutorialspoint.com/java/java_thread_communication.htm) – Hearner May 30 '18 at 08:51
  • The best would be that the threads communicate in some way. The hacky way would be to watch the process list or access the JVM threads in any other hacky way like `Thread.getAllStackTraces().keySet();`. – Zabuzard May 30 '18 at 09:09
  • Using networking you can open port on demo 2 and in the demo1 check weather anyprocess is opne on that port or not. – Akshay Pethani May 30 '18 at 09:15
  • Possible duplicate of [check if some exe program is running on the windows](https://stackoverflow.com/questions/19005410/check-if-some-exe-program-is-running-on-the-windows) – Tatranskymedved May 30 '18 at 09:26

1 Answers1

0

If I understood, you have two programs meaning two separatly threads. So you can access to the process list just like this:

Windows:

try {
    Process proc = Runtime.getRuntime().exec("process.exe");
    BufferedReader input = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    OutputStreamWriter oStream = new OutputStreamWriter(proc.getOutputStream());
    oStream.write("process where name='process.exe'");
    String line;
    while ((line = input.readLine()) != null) { 
        if (line.contains("process.exe")) 
            return true; 
    } 
    input.close(); 
} 
catch (Exception ex) { 
    // handle error 
}

Linux:

try {
    Process p = Runtime.getRuntime().exec(new String[] { "bash", "-c", "ps aux | grep process" });
    BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line;
    while ((line = input.readLine()) != null) {
        if (line.contains("process")) {
            // process is running
        }
    }
}
catch (Exception e) {
    // handle error
}

Hope it helps.

J. Lorenzo
  • 141
  • 6