How does cat know the baud rate of the serial port?

The stty utility sets or reports on terminal I/O characteristics for the device that is its standard input. These characteristics are used when establishing a connection over that particular medium. cat doesn't know the baud rate as such, it rather prints on the screen information received from the particular connection.

As an example stty -F /dev/ttyACM0 gives the current baud rate for the ttyACM0 device.


cat just uses whatever settings the port is already configured for. With this little C snippet you can see the baud rate currently set for a particular serial port:

get-baud-rate.c

#include <termios.h>
#include <unistd.h>
#include <stdio.h>

int main() {
  struct termios tios;
  tcgetattr(0, &tios);
  speed_t ispeed = cfgetispeed(&tios);
  speed_t ospeed = cfgetospeed(&tios);
  printf("baud rate in: 0%o\n", ispeed);
  printf("baud rate out: 0%o\n", ospeed);
  return 0;
}

Run it:

./get-baud-rate < /dev/ttyS0 # or whatever your serial port is

The numbers you get can be looked up in /usr/include/asm-generic/termios.h, where there are #defines such as B9600 etc. Note that the numbers in the header file and in the get-baud-rate output are in octal.

Maybe you can experiment and see what these numbers are like on a fresh boot and whether they change later.