Java 未打印过程变量输出

Java 未打印过程变量输出,java,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/b

我想要一个打印过程变量
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();
        }
    }
}

进程
没有name属性。但是您可以使用
pid

你可以这样试试

Field field=p.getClass().getField("pid"); // use reflection since pid is private
System.out.println(field);
但是你不能用

System.out.println(p)

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

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

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
,则必须启动另一个线程。

toString()
不会被Process类重写,因此您将获得
java.lang。UNIXProcess@727896
(默认实现为className@hashCode). 你期望什么样的产出?