Add shutdown hook to close all ports in native code

This commit is contained in:
Will Hedgecock 2021-12-17 10:16:34 -06:00
parent f23f844d39
commit e878f734f8
31 changed files with 14 additions and 1 deletions

View File

@ -180,6 +180,11 @@ JNIEXPORT void JNICALL Java_com_fazecast_jSerialComm_SerialPort_initializeLibrar
JNIEXPORT void JNICALL Java_com_fazecast_jSerialComm_SerialPort_uninitializeLibrary(JNIEnv *env, jclass serialComm)
{
// Close all open ports
for (int i = 0; i < serialPorts.length; ++i)
if (serialPorts.ports[i]->handle > 0)
Java_com_fazecast_jSerialComm_SerialPort_closePortNative(env, serialComm, (jlong)(intptr_t)serialPorts.ports[i]);
// Delete the cached global reference
(*env)->DeleteGlobalRef(env, serialCommClass);
}

View File

@ -450,7 +450,12 @@ JNIEXPORT void JNICALL Java_com_fazecast_jSerialComm_SerialPort_initializeLibrar
JNIEXPORT void JNICALL Java_com_fazecast_jSerialComm_SerialPort_uninitializeLibrary(JNIEnv *env, jclass serialComm)
{
// Delete the cache global reference
// Close all open ports
for (int i = 0; i < serialPorts.length; ++i)
if (serialPorts.ports[i]->handle != INVALID_HANDLE_VALUE)
Java_com_fazecast_jSerialComm_SerialPort_closePortNative(env, serialComm, (jlong)(intptr_t)serialPorts.ports[i]);
// Delete the cached global reference
(*env)->DeleteGlobalRef(env, serialCommClass);
}

View File

@ -343,6 +343,9 @@ public final class SerialPort
}
}
catch (Exception e) { e.printStackTrace(); }
// Add a shutdown hook to ensure all ports get closed
Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { uninitializeLibrary(); } });
}
// Static symbolic link testing function