Thursday, April 21, 2022
Notes on obtaining a process ID from Java on Mac OS Big Sur
There's a tool I use at work to manually test the code we work on. It's a graphical tool written in Java, and it allows us to configure the data for a test. It then runs another process that starts everything up, and then runs another tool to inject a SIP message into the code being tested. It then opens the output file from the SIP injection tool to display the results. This tool doesn't work quite right on Belial, the annoying Mac Laptop.
Problem one—the output file has, as part of its name, the process ID of the SIP injection tool. And it seems there is no easy way to get said process ID from within Java. The other issue, also related to process IDs, is it attempts to stop the process that starts everything up. That fails, because again, there is no easy way to get a process ID from within Java.
There is code that attempts to get a process ID:
process = pb.start(); if (process.getClass().getName().equals("java.lang.UNIXProcess")) { try { Field f = process.getClass().getDeclaredField("pid"); f.setAccessible(true); sippPid = f.getInt(process); } catch (Throwable e) { } }
This horrible bit of code does work under Linux,
and it works on older versions of Mac OS-X.
But Belial is a more modern version of Mac OS-X,
on the new Apple M1 architecture.
Here,
sippPid
is always 0.
Sigh.
Notes on fixing a Java issue on Mac OS Big Sur
When last we met, I was left with a broken test tool on the newer Mac laptops. The issue at hand is that it's problematic to obtain process IDs in Java, which the testing tool needs for two things. The first is an output file. It turns out one can specify the output file the SIP injection tool generates instead of the default one which uses a process ID. This also makes it easier to check the output since you don't have to grovel through the directory for an ever-changing file name. That issue fixed.
The second one—how to stop the program that runs all the programs that are being tested.
The code used the process ID to terminate that program by shelling out to run kill -SIGINT pid
.
It turns out the Java Process
object does have a destroy()
method
(it sends a SIGTERM
to a process, which is fine).
It was just a simple matter to update the code to use the destroy()
method to terminate the program rather than trying to obtain the process ID in a dodgy way.
That issue fixed.
Now all I have to do is spend a few weeks trying to get the code commited to the repository (yeah, I'm still trying to get used to the process—sigh).