0

I want to write a java program A that runs another program B and prints the stack trace of B.

I know that I can print the stack trace of A with the below code

for( i = 0; i < Thread.currentThread().getStackTrace().length; i++ ) {
            System.out.println(Thread.currentThread().getStackTrace()[i].
            getMethodName());
}

But is it possible to print the stack trace of program B if i am executing it like this from A

Process pr = Runtime.getRuntime().exec("javac B.java");
pr.waitFor();
pr = Runtime.getRuntime().exec("java B").printStackTrace();
 pr.waitFor();
Vishnu Ks
  • 483
  • 1
  • 5
  • 18

4 Answers4

1

The JDK contains the commandline tool jstack:

Prints Java thread stack traces for a Java process, core file, or remote debug server. This command is experimental and unsupported.

When you call jstack you need to provide the process id of the Java process for which you want to get a stracktrace.

You might want to experiment if you can run jstack from your master Java program.

wero
  • 32,544
  • 3
  • 59
  • 84
0

Yes. A JVM process can be accessed in different manners by another (Java) program.

A very generic way of accessing another Java program is by writing a Java agent / using the Instrumentation API. Using this API, it is possible to change a running Java program by modifying the executed code of this program. For example, you can redefine existing methods to include additional instructions that expose the stack trace any time a given execution point is reached. Alternatively, you could simply instruct to print the stack trace directly. This is also how the mentioned JStack application works.

A simpler alternative would be to expose a JMX bean from the running application that allows to trigger the printing of the stack trace.

Both access modes does however require some tricks for accessing the other VM's process ID what is not trivial in Java.

Community
  • 1
  • 1
Rafael Winterhalter
  • 42,759
  • 13
  • 108
  • 192
0

You could look into writing an Agent. There is a tutorial here. Agents let you insert code into any running java program and see what is going on. That is how remote debugging works. As an example you start JBoss or Tomcat with -agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n to insert the debugging agent. You can do the same by writing an agent and then inserting your agent into a running process at startup time.

markbernard
  • 1,412
  • 9
  • 18
-1

SHORT ANSWER:

NO

LONG ANSWER:

Program A only execute whatever program B does. it doesn't know how it does things internally. Only thing that A can know about B is whatever the B's output stream and error stream can produce. if you want to know a bit more about it (e.g. how much memory B uses and etc), you can try to find it's PID and ask OS about some information

nafas
  • 5,283
  • 3
  • 29
  • 57