过程变量输出未打印

时间:2014-08-13 12:22:25

标签: java

我想要一个用于打印过程变量p的值的解决方案。我们如何打印p的价值?目前p的值为:java.lang.UNIXProcess@727896

public class shellscript{
    public static void main(String[] args) {    
        Runtime r = Runtime.getRuntime();
        Process p = null;
        String cmd[] = {
            "/bin/bash", 
            "/home/aminul/myscript"
        };
        try { 
            p = r.exec(cmd);
            System.out.println("testing..." + p);
            System.out.println(p);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2 个答案:

答案 0 :(得分:1)

如果要记录流程的标准输出和退出代码,请尝试以下操作:

public static void main(String[] args) throws Exception
{
    final Runtime r = Runtime.getRuntime();

    final String cmd[] = { "/bin/bash", "/home/aminul/myscript" };
    try
    {
        final Process p = r.exec(cmd);

        new Thread()
        {
            public void run()
            {
                BufferedReader br = null;
                try
                {
                    br = new BufferedReader(new InputStreamReader(p.getInputStream()));
                    String line = br.readLine();
                    while (line != null)
                    {
                        System.out.println(line);
                        line = br.readLine();

                    }

                }
                catch (final Exception e)
                {
                    e.printStackTrace();
                }
                finally
                {
                    if (br != null)
                        try
                        {
                            br.close();
                        }
                        catch (final IOException ioe)
                        {
                            ioe.printStackTrace();
                        }
                }
            };

        }.start();
        p.waitFor();//wait for process to terminate
        System.out.println("Exit code: "+p.exitValue());
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

}

当然,如果您想要记录ErrorStream,则必须启动另一个帖子。

答案 1 :(得分:0)

Process没有姓名属性。但您可以使用pid

你可以这样试试

Field field=p.getClass().getField("pid"); // use reflection since pid is private
System.out.println(field);

但你不能使用

System.out.println(p)

由于Process没有覆盖toString()方法