Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get/hook/attach an already running process using java?

Tags:

java

process

I want to be able to do something like that:

Process p  = getRunningProcess(pid)

If there's a way, does it matter how the process was created (using java, using python, from the shell, etc...)?

like image 516
wafwaf Avatar asked Nov 24 '11 13:11

wafwaf


People also ask

How do I know if Java application is running?

lang. Runtime class. If you want to check the work of java application, run 'ps' command with '-ef' options, that will show you not only the command, time and PID of all the running processes, but also the full listing, which contains necessary information about the file that is being executed and program parameters.

Where should code be executed before JVM crash?

All we have to do is simply write a class that extends the java. lang. Thread class, and provide the logic that we want to perform when the VM is shutting down, inside the public void run() method.


1 Answers

It is possible to attach to another JVM process from Java app (e.g. to be able to monitor what's going on and potentially detect problems before they happen). You can do this by using the Attach API. Don't know much about attaching to non-JVM processes.

String name = ...
List vms = VirtualMachine.list();
for (VirtualMachineDescriptor vmd: vms) {
    if (vmd.displayName().equals(name)) {
        VirtualMachine vm = VirtualMachine.attach(vmd.id());
        String agent = ...
        vm.loadAgent(agent);
        // ...
    }
}
like image 84
nowaq Avatar answered Nov 11 '22 14:11

nowaq