python-3.xsubprocessraspberry-pi3rfcomm

Running an RFCOMM server in the background using subprocess


I have been trying various ways of getting an RFCOMM server up and running using python's subprocess package for some time now but have hit a wall. What I want to do is start a process in the background with this RFCOMM server running and getting the usual return from the command which is something like "Connected /dev/rfcomm0 to xx:xx:xx:xx:xx:xx on channel n" and "Press CTRL-C for hangup". The thing is, the process starts with two different ways I have tried it but getting this return and letting it sit in the background is an issue for me.

Alternative 1:

ref = Popen("sudo rfcomm connect 0 xx:xx:xx:xx:xx:xx 1 -i hci0 &", stdout=PIPE, stderr=PIPE, shell=True)

The above starts the RFCOMM server but either if I use communicate() or try to read from ref.stdout/stderr the program freezes.

Alternative 2:

res = run("sudo rfcomm connect 0 xx:xx:xx:xx:xx:xx 1 -i hci0 &", stdout=PIPE, stderr=PIPE, shell=True)

Same thing here, if I try to access the CompletedProcess objects stdout/stderr fields, the program freezes and refuses to continue. The RFCOMM server starts but the script does not terminate and I cannot read the stdout/stderr fields.

Alternative 3:

res = run(["sudo", "rfcomm", "connect", "0", "xx:xx:xx:xx:xx:xx", "1", "-i", "hci0"], stdout=PIPE, stderr=PIPE)

Same thing here, even though shell is left at its default and the command is not to be run in the background, the run function does not return and the script does not terminate. The RFCOMM server starts but the script does not terminate and I cannot read the stdout/stderr fields.

So, what I want is to start this RFCOMM server in the background, read the two lines it should show, and continue with my program so that I can poll its availability through other commands.


Solution

  • Quite strange answer in my opinion for this one, but the answer lied in that I assigned stdout and stderr to the PIPE constant. This for some reason "binds" the script to the execution and will not let it finish. When removing these two assignments the script finishes happily and I have to find another way to get the output that I in my question listed I wanted, the "Connected ..." message that is. Seems like there is no way for me to retrieve it for now.

    Script that works and starts the server in the background:

    mac_addr = "xx:xx:xx:xx:xx:xx"
    
    run("sudo rfcomm connect 0 " + mac_addr + " 1 -i hci0 &", shell=True)
    

    So, as you can see, I just removed stdout and stderr... If someone in turn can answer why that would essentially "lock" the script I would be grateful.