Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

p.waitfor() waits forever

Tags:

java

i am trying to run commands using java program,but p.waitfor() function waits forever.What is wrong with the code?

import java.io.*;

public class doscmd
{
  public static void main(String args[]) throws InterruptedException
  {
    try
    {
      Process p=Runtime.getRuntime().exec("cmd /c dir");
      p.waitFor();
      BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
      String line=reader.readLine();
      while(line!=null)
      {
        System.out.println(line);
        line=reader.readLine();
      }
    } 
    catch(IOException e1) {}


    System.out.println("Done");
  }
}
like image 469
Salih Erikci Avatar asked Jan 31 '26 22:01

Salih Erikci


1 Answers

Is the directory large? Maybe p fills up its output buffer and stalls waiting for a reader to consume something so it can finish writing out the directory listing.

You should probably move

p.waitFor();

to the end of the method.

like image 177
Mike Samuel Avatar answered Feb 02 '26 13:02

Mike Samuel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!