Click here to Skip to main content
15,666,844 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am having an issue with windows closeHandle((Handle)port) function in our .dll. it is not returning. The issue happens every few hours.

The java application using the .dll connects, reads and writes data. The last method call java application does is to write the data and release method is called IMMEDIATELY which calls closeHandle function in the JNI.

Is CloseHandle not returning because write is still happening? Is there a way to gracefully return to normal when the closeHandle hangs/ not return. Thanks in advance.

The code for the function which calls closeHandle is below.

    HANDLE port;
    jfieldID portFID = GetFieldId(env, jthis, "portnbr", "J");
    if ( portFID == 0 ){
        flog("ERROR: Java_com_hctsi_comm_Serial_close() portFID=0\n");
    port = (HANDLE)env->GetLongField(jthis, portFID);
    if ( 0 != port ) {
        flog("Java_com_hctsi_comm_Serial_close() port %d\n", port);
        int count = 0;
        while ( !CloseHandle((HANDLE)port) && count < 10 ) {
            flog("ERROR Java_com_hctsi_comm_Serial_close() closeHandle failed with an error %d\n", count, port, GetLastError);
            flog("ERROR Java_com_hctsi_comm_Serial_close() failed count %d port %d\n", count, port);
        env->SetLongField(jthis, portFID, (jlong)0);

What I have tried:

I haven't tried anything, because it is hard to replicate on my local, but It Does happen in production intermittently.
Updated 9-Aug-19 22:56pm
11917640 Member 11-Aug-19 5:32am    
The only reason I can see is incorrect handle value passed to CloseHandle. In such case, CloseHandle result is undefined.

1 solution

If you write on the port you should check that the data is written and than close the port.

It is best to open only when needed and than close again. Read about the specific timeouts of that port.

Be precise about not opened multiple ports or double close ports, this can lead to strange results. Use some internal member or set a flag.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900