1
import java.io.*;
import java.io.IOException;
import java.util.Scanner;

public class AutoStart{
    public static void main(String[] args){
        while(true){
            Runtime r = Runtime.getRuntime();
            try{
                Process p = r.exec("ps -ef >> services.txt");
                try{
                    p.waitFor();
                } catch(InterruptedException e){
                    e.getStackTrace();
                }   

                Scanner txtscan = new Scanner(new File("services.txt"));
                int running = 0; //0 means not running and 1 means running
                while(txtscan.hasNextLine()){
                    String str = txtscan.nextLine();
                    if(str.indexOf("red5") != -1){
                        running = 1;
                    }
                }

                if(running == 0){
                    //red5 is not running so start it now
                    //code to start it goes here
                }

                //at the end remove services.txt file
                //code to remove that file goes here.


            } catch(IOException e){
                e.getStackTrace();
            }

            try {
                Thread.sleep(1000);                 //1000 milliseconds is one second.
            } catch(InterruptedException ex) {
                Thread.currentThread().interrupt();
            }

        }
    }
}

On line 10 I am trying to create a text file which contains list of all the running programs but my java program is not able to create it.

This program is not able to create services.txt file and I don't get any error at all so I am confused what's the problem. Can you help me figure out the problem? Thank you.

3
  • Do you need services.txt only to pass data from command output to your Java program? It's better to use p.getInputStream() or p.getErrorStream() instead Commented Sep 20, 2015 at 8:39
  • It is highly recommended to use the full pathname (/bin/ps) as the PATH setting isn't honored. Redirection will not work either. The ProcessBuilder class provides ways for reading or redirecting the output of a program. Commented Sep 20, 2015 at 8:52
  • 1
    1. Don't use Runtime.exec(), use a ProcessBuilder. 2. either one of them WILL NOT issue the command in a shell interpreter, which is why your command won't work (>> xxx is interpreted by the command interpreter; but here those are arguments to the ps command which, of course, knows nothing of them.). Commented Sep 20, 2015 at 8:53

2 Answers 2

1

This calls a subprocess without relying on any shell mechanism, catching the resulting standard output.

public static void main( String[] args ) throws Exception {
  try { 
    ProcessBuilder pb = new ProcessBuilder( "/bin/ps", "-ef" );
    Process process = pb.start();
    InputStream is = process.getInputStream();
    Reader rdr = new InputStreamReader( is );
    LineNumberReader lnr = new LineNumberReader(rdr);
    String line;
    while( (line = lnr.readLine()) != null ){
      if( line.contains( "skype" ) ){
        System.out.println( "skype is running" );
      }
    }
    process.waitFor();
  } catch( Exception e ){

  } catch( Error e ){

}
Sign up to request clarification or add additional context in comments.

2 Comments

Uh, not rethrowing errors? Also, why don't you use try-with-resources?
No, but then this is 2015 and try-with-resources has been with us for 4 years
1

InuThe Process class will not throw an exception if your command returns a non-zero exit code (usually indicating failure). You have to dig into it yourself.

Here is a basic change to your code that will print the error and output stream (command line tools may print to either) to the console upon receiving a non-zero exit code from the process.

Hopefully this helps you figure it out:

import java.io.*;
import java.io.IOException;
import java.util.Scanner;

public class AutoStart{
    public static void main(String[] args){
        while(true){
            Runtime r = Runtime.getRuntime();
            try{
                Process p = r.exec("ps -ef >> services.txt");
                try{
                    p.waitFor();
                } catch(InterruptedException e){
                    e.getStackTrace();
                }

                if (p.exitValue() != 0){

                    BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()));

                    System.out.println("Error Stream:");

                    String line;

                    while ((line = br.readLine()) != null){
                        System.out.println(line);
                    }

                    br = new BufferedReader(new InputStreamReader(p.getInputStream()));

                    System.out.println("Output Stream:");

                    while ((line = br.readLine()) != null){
                        System.out.println(line);
                    }

                    System.exit(1);
                }

                Scanner txtscan = new Scanner(new File("services.txt"));
                int running = 0; //0 means not running and 1 means running
                while(txtscan.hasNextLine()){
                    String str = txtscan.nextLine();
                    if(str.indexOf("red5") != -1){
                        running = 1;
                    }
                }

                if(running == 0){
                    //red5 is not running so start it now
                    //code to start it goes here
                }

                //at the end remove services.txt file
                //code to remove that file goes here.


            } catch(IOException e){
                e.getStackTrace();
            }

            try {
                Thread.sleep(1000);                 //1000 milliseconds is one second.
            } catch(InterruptedException ex) {
                Thread.currentThread().interrupt();
            }

        }
    }
}

2 Comments

AutoStart.java:29: error: incompatible types: OutputStream cannot be converted to InputStream In this line br = new BufferedReader(new InputStreamReader(p.getOutputStream()));
@user3774654 My mistake, accidentally put getOutputStream() when I meant, getInputStream(). I fixed my post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.