Search code examples
javatasklist

Java " tasklist.exe /fo csv /nh"command taking forever to load in process waitFor


I am calling method command in main() by command(" tasklist.exe /fo csv /nh");

This is my code snippet :

String command(String command)throws Exception
    {long start=System.currentTimeMillis();
        System.out.println(" Entered command execution starting , executing : "+command);
        String output="";
        //A string for accumulating the output given by command executed
        System.out.println(" On line 1 ");
 Process powerShellProcess = Runtime.getRuntime().exec(command);

  System.out.println(" On line 2 ");
  //Executing our command by Process
 powerShellProcess.waitFor();
  System.out.println(" On line 3 ");
  //Waiting for it to complete 
  powerShellProcess.getOutputStream().close();
  System.out.println(" On line 4 ");
  //Closing Output Stream
  String line;
  //A string for each line accumulation of standard output in while loop
  BufferedReader stdout = new BufferedReader(new InputStreamReader(
    powerShellProcess.getInputStream()));
    //BufferedReader for getting standard output given by command .
  while ((line = stdout.readLine()) != null) {
output+=line+",";
//Adding line by line output to String output
  }
  stdout.close();
  //Closing BufferedReader stdout
  BufferedReader stderr = new BufferedReader(new InputStreamReader(
    powerShellProcess.getErrorStream()));
    //BufferedReader for getting standard error given by command ( if any ).
    stderror="";
      //A string for each line accumulation of standard error in while loop
  while ((line = stderr.readLine()) != null) {
      stderror+=line;
      //Adding line by line standard error to String stderror
  }
  stderr.close();
  //Closing BufferedReader stderr
  long end=System.currentTimeMillis();
  System.out.println(" Ending command execution starting in "+(end-start)+" milliseconds . ");
  System.out.println(" Error : ");
  System.out.println(stderror);
  System.out.println(" Output : ");
  System.out.println(output);
  return output;
  //Returning standard output by command 
    }

Its stuck in waitFor() and taking forever to load up , I can't figure out .

The output of code is below : On line 1 On line 2

Further help will be highly appreciated .


Solution

  • Try to remove .waitFor() , but I give you a warning removing it can result in incomplete/empty outputs as its not waiting for it to return output . So better consider waiting or while process isActive() append output to a stringBuilder and print it afterwards .