Search code examples
javalinuxprocesssubprocessrfcomm

Killing subprocess started insinde new terminal


I have java program that spawns a new subprocess which itself executes a command in a new terminal window:

Process proc = Runtime.getRuntime().exec("lxterminal -e sudo rfcomm watch " + BLUETOOTH_CHANNEL);.

rfcomm watch *CHANNEL* watches the declared channel/linux device file for incoming data via bluetooth in my case. When the connection is canceled, I want to be able to restore it later in the program on the same device file. Since rfcomm watch blocks the declared device file it has to be closed before the same command runs again. This can manually by achieved by sending SIGTERM to the process (Ctrl + c inside the newly spawned terminal window).

My problem is that when I do proc.destroy() or proc.destroyForcibly() it seems like only the terminal is killed and rfcomm watch is still running (which results in an error message when trying to watch the same device file again). rfcomm watch also still appears under ps.

How do I kill both the new terminal window and the command running inside it programmatically?


Solution

  • I have found a solution/workaround which fits my purpose but might not be suitable for problems that are akin.

    Since I want to kill the process that blocks the rfcomm channel I declared and don't use other channels and do not care if anything else rfcomm-related gets killed, I simply run the line Runtime.getRuntime().exec("sudo pkill rfcomm"); in a shutdown-hook. This works for me.

    If it is important to kill only one specific process, something like this can be done: How to give arguments to kill via pipe