stty device baud-rate resets once no longer being used

For anyone who stumble upon this (yes, another...), here a shell solution (Bash at least):

The 'trick' is to open a file descriptor for the serial port before using stty. And keeps it open during all the reading/writing.

Example:

exec 3<>/dev/cu.xxxxxxxx           # open a file descriptor
stty -f /dev/cu.xxxxxxxx raw 19200 # configure the serial port
cat /dev/cu.xxxxxxxx               # do stuff...
exec 3<&-                          # close the file descriptor

Thanks to @crasysim for his comment on the same question.


For anyone who may later stumble upon this, I was not able to find any trick to help keep a set baud-rate "stick" using stty -f /dev/cu.xxxxxxxx 19200. I ended up writing a simple little C program that would open() and sleep() indefinitely while I performed any other bash magic, which effectively emulated what I originally wanted.


I was having a similar issue and the answer you posted got me thinking about whether there was a way to run stty and then another command before stty exited. This is essentially what piping does albeit with the stdin and stdout linked together which is irrelevant in this instance.

From my experimentation, the following will allow you to change the cu config and then access it with those settings.

stty -f /dev/cu.xxxxxxxx 115200|cat /dev/cu.xxxxxxxx