質問

I have a java application that reads data from a serial port /dev/ttyUSB0. This application runs on Linux, using RXTX library to access the serial port from java.
Sometimes the serial port isn't closed properly by a worker thread, and when starting a new one I get javax.comm.PortInUseException. Worker threads get stuck while calling close() method. This has already been asked but I cannot directly apply that hack.
Is there a way to force Linux to close the port? I can call external processes and run shell scripts as root. Once the port is closed by the OS, I intend to handle the proper exception in java.
I can't reboot the machine.

役に立ちましたか?

解決

I actually faced this problem at work a few months back (at least it looks a lot like it). I spent a lot of time (like a week) on it. I looked through the native code and found the issue (it's in the RXTX lib).

I'm going to recommend you implement the same solution I did - manage your threads and your ports properly! You shouldn't be relying on PortInUseException to check if a port is opened anyway - that's for 'exceptional' cases.

Just make sure you:

  1. Always call close on an opened port
  2. Never call open on an opened port

If you'd rather work around it than do it the right way - the issue is in the native app, so you need to find a way to 'restart' it. In my case it was all inside an OSGi framework so I could just uninstall the bundle that contained the native app and then install it again. In your case it might require restarting the whole Java process

他のヒント

First, you should debug your code and make sure that the thread responsible for closing the device node really does close it; since you're talking about access to a non-shareable hardware device, using the Holder pattern for the RXTX connection might be helpful.

If the program isn't properly closing the device node, the only option is to kill it. You can use fuser /dev/ttyUSB0 to see what process has it open and then kill that PID. This doesn't require root privileges, just access as the user who owns the process to be killed.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top