1. Depending on how you started the process, the name of the process will be "java.exe" or "javaw.exe". From within your program, you can request the process ID (PID) with the following Java code:
import java.lang.management.RuntimeMXBean;
import java.lang.management.ManagementFactory;
public static String processID()
{
RuntimeMXBean rmxb = ManagementFactory.getRuntimeMXBean();
return rmxb.getName();
}
You can use this Java code by including it as "inline Java code" in your B4J code. You will need the PID to terminate the process, as you'll see in answer 4.
2. As far as I know, no, you cannot. The name of the process is the same as the name of the executable that spawned the process. In this case, the name of the executable is the java.exe or javaw.exe, depending on how you started the process.
3. If you want this process to be started as soon as you log into Windows, place a batch file in the following folder:
C:\Users\<YourUserName>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
In this batch file, place the following text:
cd C:\Directory\Of\Your\Jar\File
javaw -jar <NameOfJarFile.jar>
4. To terminate any process from within a Java application, call:
public static boolean killProcessByPID(String pid)
{
String cmd = "taskkill /F /PID " + pid;
try {
Runtime.getRuntime().exec(cmd);
return true;
} catch (IOException ex) {
System.err.println("Failed to kill PID: " + pid);
System.err.println(ex.getMessage());
return false;
}
}
using the same "inline Java code" method as in answer 1. This code is the same as calling
from the command line. You can also kill a process from within Windows Task Manager by right-clicking on it. If you want to kill a B4J app from within the same app, call
. If you want to start a Java process, you can double-click on the .jar file or call the same commands from the command line as are in the batch file from answer 3.
You can also get a Java process to restart itself as follows:
public static boolean launchWithDelay(String jarName)
{
String cmd = "timeout 10 \njavaw -jar " + jarName;
try {
Runtime.getRuntime().exec(cmd);
return true;
} catch (IOException ex) {
System.err.println("Failed to launch .jar: " + jarName);
System.err.println(ex.getMessage());
return false;
}
}
Include this function in your B4J code using "inline Java code" and then run
Sub relaunchSelf(selfJarName)
launchWithDelay(selfJarName)
ExitApplication
End Sub
in your B4J code to restart a Java process from within the process. Note that the jarName you pass the function must include the ".jar" suffix. Also, this will only work to launch a .jar in the same directory as the calling .jar (namely, itself).
Note that you can also run these commands from within a B4J app using the jShell library.
EDIT: Make sure the inline Java methods are static, as they are now. They weren't when I first wrote this essay.