Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 脚本被挂起并且没有给出任何输出_Java_Multithreading_Shell - Fatal编程技术网

Java 脚本被挂起并且没有给出任何输出

Java 脚本被挂起并且没有给出任何输出,java,multithreading,shell,Java,Multithreading,Shell,我返回了一个脚本,它在执行时修改一个文件中的一行 工作脚本的流程来自打印检查点111后的run方法。打印检查点aaaa后,它将转到executeCmd方法,执行再次转到run方法打印检查点222,返回executeCmd方法,并在打印bbb后退出执行 但在我的例子中,在检查点aaa之后,它正在打印检查点bbb,这个循环永远不会结束,所以执行不会返回到run方法,因此脚本被卡住并挂起会话 public String executeCmd(String classOpts, String cmdLi

我返回了一个脚本,它在执行时修改一个文件中的一行

工作脚本的流程来自打印检查点111后的run方法。打印检查点aaaa后,它将转到executeCmd方法,执行再次转到run方法打印检查点222,返回executeCmd方法,并在打印bbb后退出执行

但在我的例子中,在检查点aaa之后,它正在打印检查点bbb,这个循环永远不会结束,所以执行不会返回到run方法,因此脚本被卡住并挂起会话

public String executeCmd(String classOpts, String cmdLine, String[] opts)
{   
    while (myCmd.isAlive() == true)
    {   
        try
        {
            log.debug("checkpoint aaaa");
            Thread.sleep(100);
            log.debug("checkpoint bbbb");
        }
    }
    exitVal = myCmd.getCmdExitValue();
    log.debug("The script exit code: = " + exitVal);
}

public void run()
{
    Runtime rt = Runtime.getRuntime();
    try
    {
        String sCommand = cmdUtils.sScriptLauncher + " " + this.cmdline;
        proc = rt.exec(cmdUtils.sScriptLauncher + " " + this.cmdline;
        proc = rt.exec(cmdUtils.ParseCommandLine(sCommand));            
        try
        {
            log.debug("Checkpoint 111");    
            cmdExitVal = proc.waitFor();`enter code here`
            log.debug("Checkpoint 222");    
        } 
//remaining code

我使用下面的类
RunProcessCMD
,它使用
ProcessBuilder
stdout
stderr

class RunProcessCMD {  


    static BufferedReader stdout, stderr;
    private Boolean isWaitFor = true;// wait for reply from CMD

    private static RunProcessCMD startRunProcessCMD = null;

    private String[] input = null;
    private static boolean isRealTime = false;

    private static StringBuilder buff = null;

    public static RunProcessCMD getInstance(){
        if(startRunProcessCMD == null){
            startRunProcessCMD = new RunProcessCMD();
        }

        return startRunProcessCMD;
    }

    private RunProcessCMD(){}// destroy public constructor 

    public void start(String[] command) throws IOException {
        buff = new StringBuilder();


         System.out.println(Arrays.asList( command ) );

        ProcessBuilder launcher = new ProcessBuilder();
        launcher.redirectErrorStream(true);


        launcher.command(command);

        launcher.start(); // And launch a new process


        buff.append("Done").append("\n");System.out.println("Done.");


    }

    public void start () throws IOException, InterruptedException{

          buff = new StringBuilder();

                    if(input == null){
                     buff.append("Command == null");

                     return;            
                    }

           //String[] input = new String[] {"tasklist"};

           Runtime r = Runtime.getRuntime();

           //System.out.println("Execute ...");

           //Process p = r.exec("cmd /c", input, null);
           System.out.println(Arrays.asList( input ) );
           Process p = r.exec(input);


           //System.out.println("Finish to execute, start read output");

           InputStream is = p.getInputStream();
           stdout = new BufferedReader(new InputStreamReader(is));
           is = p.getErrorStream();
           stderr = new BufferedReader(new InputStreamReader(is));

           //outputLines = new Vector();

           if( isWaitFor == true ){
            StdoutThread cltOut = RunProcessCMD.getInstance().new StdoutThread();   
            Thread tOut = new Thread(cltOut);
            tOut.start();

            StderrThread cltErr = RunProcessCMD.getInstance().new StderrThread();   
            Thread tErr = new Thread(cltErr);
            tErr.start();

            p.waitFor();
           }



           buff.append("Done").append("\n");System.out.println("Done.");

           if( isWaitFor == false ){
            buff.append("WaitFor defined to be false, respectivally no output from CMD").append("\n");
            System.out.println("WaitFor defined to be false, respectively no output from CMD");
           }

         }

    private  class StdoutThread implements Runnable {
        @Override
        public void run() {
            try {
                int l;
                String line;

                for(l = 0; (line = stdout.readLine()) != null; ) {
                    if (line.length() > 0) 
                        l++;
                        //outputLines.addElement(line);
                        buff.append(line).append("\n");

                    if(!line.trim().equals("")){
                            System.out.println(line);
                        }
                }
                stdout.close();
            } 
            catch(IOException ie) { 
                buff.append("IO exception on stdout: " + ie).append("\n");
            }
        }
    }


    private  class StderrThread implements Runnable {

        public StderrThread() {}

        @Override
        public void run() {
            try {
                int l;
                String line;
                for(l = 0; (line = stderr.readLine()) != null; ) {
                    if (line.length() > 0) l++;
                    buff.append(line).append("\n");                                     
                        System.out.print(line);

                }
                stderr.close();
            } 
            catch(IOException ie) { 
                buff.append("IO exception on stdout: " + ie).append("\n");//System.out.println("IO exception on stdout: " + ie);
            }
        }
    }

    public static void ClearBuff (){
        buff.setLength(0);
        isRealTime = false;
    }

    public void setInput(String[] input) {
        // reset flag
        isWaitFor = true;

        if(input[input.length-1].contains("waitFor") && input[input.length-1].split("=").length == 2 ){

            String bull = input[input.length-1].split("=")[1];

            isWaitFor = new Boolean( bull ); 

            System.out.println("isWaitFor = " + isWaitFor);

            // remove last value from String array
            String[] input_new = new String[input.length -1];

            for(int k=0; k < input_new.length; k++){
                input_new[k] = input[k];
            }

            input = input_new;

        }

        // add proper value for input       
        String[] str = new String[input.length + 2];
        str[0] = "cmd.exe";
        str[1] = "/c";

        for(int i=2; i<str.length; i++){
            str[i] = input[i-2];
        }

        this.input = str;
    }

    public static StringBuilder getBuff() {

        if( buff == null ){
          return new StringBuilder( "" );
        }

        return buff;
    }

    public void setRealTime(boolean b) {
        isRealTime  = b;
    }   

} 

请帮我解决这个问题,我已经花了整整两天的时间尝试不同的场景,但都没有出现问题,我怀疑问题出在等待方法或线程中。睡眠此代码没有编译,是吗?1。不要使用
Runtime.exec()
,使用
ProcessBuilder
;2.您不会对脚本的stdout和stderr执行任何操作:如果脚本输出任何内容,它将阻塞。
private void runSomeCommandOverCmd(){


    String runP = "adb devices";


    String[] strArr = new String[2];
    strArr[0] = runP;
    strArr[1] = "waitFor=true";

    RunProcessCMD.getInstance().setInput( strArr );

    try {
        RunProcessCMD.getInstance().start();

        String str = ( RunProcessCMD.getBuff() ).toString();

        System.out.println(str);

        RunProcessCMD.ClearBuff();

    } catch (Exception e) {
        try {
            throw new Exception( "Failed to Start process CMD" );
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }           

}