PC to PC Communication in C: Serial Port Chat on Linux and Windows

Build a two-way serial chat between two PCs in C, from the null-modem wiring to raw-mode ports, message framing and error detection that works.

Two computer monitors connected by a three-wire null-modem cable whose transmit and receive wires cross.

A serial cable at 115200 baud moves 11,520 bytes per second, and none of those bytes says where a message starts, where it ends, or whether it arrived intact. Two PCs can talk over three wires with a few dozen lines of C, but a program that works reliably has to add those three things itself.

This guide builds a working chat program for two computers joined by a null-modem cable or a pair of USB-to-serial adapters. It covers the wiring, opening and configuring the port on Linux (termios) and on Windows (the Win32 API), framing messages so the receiver can find them, and a CRC that catches damaged ones. Every program was compiled and run for this article on Ubuntu 24.04 with GCC 13.3 and Clang 18 under -std=c11 and -std=c17 with -Wall -Wextra -pedantic and zero warnings, with clean AddressSanitizer and UndefinedBehaviorSanitizer runs, and the Windows code was cross-compiled with MinGW-w64 under the same flags. Output blocks come from real runs, two of them over a pair of virtual serial ports, since no physical cable was involved. The deliberately broken examples in the mistakes section are shown with their compiler output.

The Short Answer

Can two PCs still talk over a serial cable in C? Yes. Most PCs no longer have a serial port, but a USB-to-serial adapter appears as /dev/ttyUSB0 on Linux or COM3 on Windows, and standard C plus the operating system’s serial API is all you need.

What cable do I need? A null-modem cable, or a three-wire cable that crosses transmit and receive and joins the grounds. Two adapters with such a cable between them work the same way.

Does the Turbo C bioscom() approach still work? No. It relies on DOS headers and direct hardware port access that modern compilers and operating systems do not provide. The program fails at the first #include, as shown later.

Is a serial link reliable? Only as reliable as your protocol makes it. The bytes arrive in order, but a byte can be damaged, lost or invented by noise, and reads return whatever happens to have arrived. This article’s framing rejected every 1-bit, 2-bit and short-burst error it was given.

What Is PC to PC Serial Communication?

PC to PC serial communication sends data between two computers one bit at a time over a cable, using a UART (universal asynchronous receiver-transmitter) on each end. Both sides must agree on the speed (baud rate), the byte format, usually 8 data bits, no parity and 1 stop bit (8N1), and whether flow control is used.

The link is the simplest connection two computers can have: no addresses, no network stack, no drivers beyond the port itself. That is why it is still used for embedded boards, lab instruments, industrial equipment and console access to routers, and why it is a good way to learn what a protocol has to do. Everything a network gives you for free, such as message boundaries, error detection and retransmission, is missing, so you see each piece being added.

Wiring: The Three-Wire Null-Modem Cable

A PC’s serial port is wired as a DTE (data terminal equipment): it transmits on pin 3 and receives on pin 2 of a DE-9 connector. Connect two PCs pin-for-pin and both would transmit into each other’s transmit pin. A null-modem cable crosses them:

Three-wire null-modem cable PC A DE-9 serial connector 2 RXD (receive) 3 TXD (transmit) 5 GND (ground) pins 1, 4, 6-9 not connected PC B DE-9 serial connector 2 RXD (receive) 3 TXD (transmit) 5 GND (ground) pins 1, 4, 6-9 not connected transmit crosses to receive ground to ground No RTS/CTS or DTR/DSR wires, so hardware flow control must be off on both ends. Both ends must also agree on the settings: here 115200 baud, 8 data bits, no parity, 1 stop bit.
Figure 1: A three-wire null-modem cable. Each PC’s transmit pin goes to the other’s receive pin, and the grounds are joined. With no handshake wires, flow control is switched off in software.
Pin on PC ASignalConnects to on PC B
2RXD (receive)3 (TXD)
3TXD (transmit)2 (RXD)
5GND (signal ground)5 (GND)

Full null-modem cables also cross the handshake lines (RTS/CTS and DTR/DSR). A three-wire cable leaves them out, so the software must not wait for them: hardware flow control has to be off on both ends, which is what the code below does.

The Portable Interface

The chat program only needs four operations, so they sit behind a small interface with one implementation per operating system. The rest of the code never sees a file descriptor or a Windows HANDLE:

#ifndef SERIAL_H
#define SERIAL_H

#include <stdbool.h>
#include <stddef.h>

/* One serial port, opened as 8 data bits, no parity, 1 stop bit, no flow control. */
typedef struct serial_port serial_port;

/* device: "/dev/ttyUSB0" on Linux, "COM3" on Windows. Returns NULL and fills err on failure. */
serial_port *serial_open(const char *device, long baud, char *err, size_t err_len);

/* Writes every byte or returns false. */
bool serial_write_all(serial_port *port, const void *data, size_t len);

/* Waits up to timeout_ms for data. Returns bytes read, 0 on timeout, -1 on error. */
long serial_read(serial_port *port, void *buf, size_t len, int timeout_ms);

void serial_close(serial_port *port);

#endif

serial_port is an opaque type: callers hold a pointer to it but cannot see its fields, which is a common C pattern for hiding platform details (see pointers in C if the serial_port * return type is unfamiliar). serial_read takes a timeout because a serial port has no “end of message” signal: the only way to know nothing more is coming is to stop waiting.

Opening a Serial Port on Linux (termios)

On Linux and macOS a serial port is a terminal device, and the termios interface configures it. A terminal’s default settings are built for a human typing at a keyboard, so the first job is to turn all of that off:

/* Serial port access for Linux and macOS, using termios. */
#define _DEFAULT_SOURCE
#include "serial.h"

#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>

struct serial_port {
    int fd;
};

static speed_t baud_constant(long baud)
{
    switch (baud) {
    case 9600:   return B9600;
    case 19200:  return B19200;
    case 38400:  return B38400;
    case 57600:  return B57600;
    case 115200: return B115200;
    default:     return 0;
    }
}

serial_port *serial_open(const char *device, long baud, char *err, size_t err_len)
{
    speed_t speed = baud_constant(baud);
    if (speed == 0) {
        snprintf(err, err_len, "unsupported baud rate %ld", baud);
        return NULL;
    }

    /* O_NOCTTY: this port must not become our controlling terminal. */
    int fd = open(device, O_RDWR | O_NOCTTY);
    if (fd < 0) {
        snprintf(err, err_len, "%s: %s", device, strerror(errno));
        return NULL;
    }

    struct termios tio;
    if (tcgetattr(fd, &tio) != 0) {
        snprintf(err, err_len, "%s: not a terminal device: %s", device, strerror(errno));
        close(fd);
        return NULL;
    }

    /* Raw mode: no line editing, no echo, no CR/LF translation, no signals. */
    tio.c_iflag &= ~(tcflag_t)(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON | IXOFF);
    tio.c_oflag &= ~(tcflag_t)OPOST;
    tio.c_lflag &= ~(tcflag_t)(ECHO | ECHONL | ICANON | ISIG | IEXTEN);

    /* 8N1, ignore modem-control lines, enable the receiver. */
    tio.c_cflag &= ~(tcflag_t)(CSIZE | PARENB | CSTOPB);
    tio.c_cflag |= CS8 | CLOCAL | CREAD;
#ifdef CRTSCTS
    tio.c_cflag &= ~(tcflag_t)CRTSCTS;   /* a three-wire cable has no RTS/CTS */
#endif

    /* read() returns whatever is available; poll() does the waiting. */
    tio.c_cc[VMIN] = 0;
    tio.c_cc[VTIME] = 0;

    if (cfsetispeed(&tio, speed) != 0 || cfsetospeed(&tio, speed) != 0 ||
        tcsetattr(fd, TCSANOW, &tio) != 0) {
        snprintf(err, err_len, "%s: cannot configure: %s", device, strerror(errno));
        close(fd);
        return NULL;
    }
    tcflush(fd, TCIOFLUSH);           /* drop anything received before we were ready */

    serial_port *port = malloc(sizeof *port);
    if (port == NULL) {
        snprintf(err, err_len, "out of memory");
        close(fd);
        return NULL;
    }
    port->fd = fd;
    return port;
}

bool serial_write_all(serial_port *port, const void *data, size_t len)
{
    const unsigned char *p = data;
    while (len > 0) {
        ssize_t n = write(port->fd, p, len);
        if (n < 0) {
            if (errno == EINTR)
                continue;
            return false;
        }
        p += n;
        len -= (size_t)n;
    }
    return true;
}

long serial_read(serial_port *port, void *buf, size_t len, int timeout_ms)
{
    struct pollfd pfd = {.fd = port->fd, .events = POLLIN};
    int ready = poll(&pfd, 1, timeout_ms);
    if (ready < 0)
        return errno == EINTR ? 0 : -1;
    if (ready == 0)
        return 0;
    ssize_t n = read(port->fd, buf, len);
    if (n < 0)
        return errno == EINTR || errno == EAGAIN ? 0 : -1;
    if (n == 0 && (pfd.revents & POLLHUP))
        return -1;                     /* the other end went away */
    return (long)n;
}

void serial_close(serial_port *port)
{
    if (port != NULL) {
        close(port->fd);
        free(port);
    }
}

The flags that matter:

  • O_NOCTTY stops the port from becoming the program’s controlling terminal, so line noise cannot send it a hang-up or interrupt signal.
  • Raw mode clears line buffering (ICANON), echo, signal characters (ISIG), CR/LF translation (ICRNL, OPOST) and software flow control (IXON, IXOFF). These are the same changes cfmakeraw() makes; they are written out here because cfmakeraw is a BSD extension rather than standard POSIX. The mistakes section shows what happens to binary data without them.
  • CS8 | CLOCAL | CREAD selects 8 data bits, ignores the modem-control lines a three-wire cable does not have, and enables the receiver. CRTSCTS (hardware flow control) is cleared where the system defines it.
  • VMIN = 0, VTIME = 0 make read() return immediately with whatever has arrived; poll() does the waiting, which gives a precise timeout in milliseconds.
  • tcflush discards anything that arrived before the program was ready.

Testing without a cable

A pseudo-terminal pair behaves like two serial ports joined by a cable, so the same code can be tested on any Linux machine. This program opens one end with serial_open() and sends a framed message each way, including the bytes a terminal in its default mode would change or swallow (CR, LF, Ctrl-C, XON, XOFF, DEL, a zero byte and the two framing codes):

Output of pty_loopback:

B received: "hello from A"
A received 11 bytes, identical to what B sent: yes
serial_read with nothing to receive returned 0

All 11 bytes arrived unchanged, and serial_read returned 0 when its 100 ms timeout expired with nothing to read.

Opening a Serial Port on Windows (Win32 API)

Windows exposes serial ports through the same CreateFile, ReadFile and WriteFile calls used for files, plus a DCB structure for the line settings and COMMTIMEOUTS for read timing:

/* Serial port access for Windows, using the Win32 communications API. */
#define WIN32_LEAN_AND_MEAN
#include <windows.h>

#include "serial.h"

#include <stdio.h>
#include <stdlib.h>

struct serial_port {
    HANDLE handle;
};

static void win_error(char *err, size_t err_len, const char *what)
{
    snprintf(err, err_len, "%s failed (Windows error %lu)", what, (unsigned long)GetLastError());
}

serial_port *serial_open(const char *device, long baud, char *err, size_t err_len)
{
    /* "\\.\COM10": names above COM9 only open with the device-namespace prefix. */
    char path[64];
    snprintf(path, sizeof path, "\\\\.\\%s", device);

    HANDLE h = CreateFileA(path, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
    if (h == INVALID_HANDLE_VALUE) {
        win_error(err, err_len, "CreateFile");
        return NULL;
    }

    DCB dcb;
    SecureZeroMemory(&dcb, sizeof dcb);
    dcb.DCBlength = sizeof dcb;
    if (!GetCommState(h, &dcb)) {
        win_error(err, err_len, "GetCommState");
        CloseHandle(h);
        return NULL;
    }
    dcb.BaudRate = (DWORD)baud;
    dcb.ByteSize = 8;
    dcb.Parity = NOPARITY;
    dcb.StopBits = ONESTOPBIT;
    dcb.fBinary = TRUE;
    dcb.fParity = FALSE;
    dcb.fOutxCtsFlow = FALSE;              /* a three-wire cable has no handshake lines */
    dcb.fOutxDsrFlow = FALSE;
    dcb.fDsrSensitivity = FALSE;
    dcb.fDtrControl = DTR_CONTROL_ENABLE;
    dcb.fRtsControl = RTS_CONTROL_ENABLE;
    dcb.fOutX = FALSE;                     /* no XON/XOFF: binary data may contain those bytes */
    dcb.fInX = FALSE;
    dcb.fNull = FALSE;
    dcb.fAbortOnError = FALSE;
    if (!SetCommState(h, &dcb)) {
        win_error(err, err_len, "SetCommState");
        CloseHandle(h);
        return NULL;
    }
    PurgeComm(h, PURGE_RXCLEAR | PURGE_TXCLEAR);

    serial_port *port = malloc(sizeof *port);
    if (port == NULL) {
        snprintf(err, err_len, "out of memory");
        CloseHandle(h);
        return NULL;
    }
    port->handle = h;
    return port;
}

bool serial_write_all(serial_port *port, const void *data, size_t len)
{
    const unsigned char *p = data;
    while (len > 0) {
        DWORD chunk = len > 65536 ? 65536 : (DWORD)len;
        DWORD written = 0;
        if (!WriteFile(port->handle, p, chunk, &written, NULL) || written == 0)
            return false;
        p += written;
        len -= written;
    }
    return true;
}

long serial_read(serial_port *port, void *buf, size_t len, int timeout_ms)
{
    /* Return as soon as any byte arrives, or after timeout_ms with nothing. */
    COMMTIMEOUTS t = {0};
    t.ReadIntervalTimeout = MAXDWORD;
    t.ReadTotalTimeoutMultiplier = MAXDWORD;
    t.ReadTotalTimeoutConstant = timeout_ms > 0 ? (DWORD)timeout_ms : 1;
    if (!SetCommTimeouts(port->handle, &t))
        return -1;

    DWORD got = 0;
    DWORD want = len > 65536 ? 65536 : (DWORD)len;
    if (!ReadFile(port->handle, buf, want, &got, NULL))
        return -1;
    return (long)got;
}

void serial_close(serial_port *port)
{
    if (port != NULL) {
        CloseHandle(port->handle);
        free(port);
    }
}

Three details trip people up on Windows:

  • Port names above COM9 only open with the device-namespace prefix, so the code always opens \\.\COM3 rather than COM3. The prefix works for every port number.
  • Every field of the DCB matters. GetCommState loads the port’s current settings, which may include hardware or XON/XOFF flow control left over from another program, so the code sets each relevant flag explicitly. The DCB documentation lists them all.
  • COMMTIMEOUTS decide how ReadFile waits. With ReadIntervalTimeout and ReadTotalTimeoutMultiplier both MAXDWORD, ReadFile returns as soon as any byte arrives, or after ReadTotalTimeoutConstant milliseconds with nothing. That matches the Linux version’s behavior.

The Windows code was compiled with MinGW-w64 under -Wall -Wextra -pedantic -Werror and builds with MSVC in the repository’s workflow; it was not run against a physical COM port (see “What I Verified”).

Bytes Are Not Messages: Framing with SLIP and CRC-16

A serial port delivers a stream of bytes. One read() may return half a message, or the end of one message and the start of the next, and nothing in the stream marks the boundary. If noise damages a byte, nothing reports it. The receiver needs two things the hardware does not provide: a way to find message boundaries, and a way to detect damage.

This code uses SLIP framing from RFC 1055: a special END byte (0xC0) marks the boundaries, and an escape byte (0xDB) is used to send END or ESC values that appear inside the data. SLIP itself has no error detection, so each message carries a CRC-16 that the receiver recomputes. Here is one message on the wire:

One message on the wire PAYLOAD (5 BYTES) 48 69 C0 21 DB “Hi”, END, “!”, ESC two bytes that collide with the framing codes ON THE WIRE (11 BYTES) C0 48 69 DB DC 21 DB DD C1 DA C0 END payload, escaped CRC-16 END C0 = ENDstarts and ends every frame; never appears inside one C0 in data → DB DCescaped so it cannot end the frame early DB in data → DB DDescaped so the escape byte itself is unambiguous C1 DACRC-16/CCITT-FALSE of the 5 payload bytes, high byte first
Figure 2: How the framing code sends a 5-byte message. END bytes mark the boundaries, escape sequences keep END out of the data, and a CRC-16 lets the receiver reject damaged frames. Bytes are from the frame_demo output.
#ifndef FRAME_H
#define FRAME_H

#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>

/* SLIP framing (RFC 1055) with a CRC-16 appended to every message. */
#define FRAME_END      0xC0
#define FRAME_ESC      0xDB
#define FRAME_ESC_END  0xDC
#define FRAME_ESC_ESC  0xDD

#define FRAME_MAX_PAYLOAD 256
/* Worst case: every byte of payload and CRC escaped, plus two END bytes. */
#define FRAME_ENCODED_MAX(n) (2 + 2 * ((n) + 2))

/* CRC-16/CCITT-FALSE: polynomial 0x1021, initial value 0xFFFF. */
uint16_t crc16_ccitt(const uint8_t *data, size_t len);

/* Returns the number of bytes written to out, or 0 if len is 0 or too large, or out_cap is too small. */
size_t frame_encode(const uint8_t *payload, size_t len, uint8_t *out, size_t out_cap);

typedef enum {
    FRAME_NONE,        /* no complete frame yet */
    FRAME_OK,          /* a valid frame: see payload and len */
    FRAME_BAD_CRC,     /* a frame arrived but its CRC did not match: discarded */
    FRAME_TOO_LONG,    /* more bytes than FRAME_MAX_PAYLOAD + 2 before END: discarded */
    FRAME_BAD_ESCAPE,  /* ESC followed by something other than ESC_END or ESC_ESC */
    FRAME_EMPTY        /* a CRC with no payload: messages are 1 to FRAME_MAX_PAYLOAD bytes */
} frame_result;

typedef struct {
    uint8_t buf[FRAME_MAX_PAYLOAD + 2];
    size_t len;
    bool escaped;
    bool broken;       /* the frame in progress is already known to be bad */
    frame_result broken_reason;
} frame_decoder;

void frame_decoder_init(frame_decoder *d);

/* Feeds one received byte. On FRAME_OK, *payload and *len describe the message
   (valid until the next call). Bytes before the first END are treated as noise. */
frame_result frame_decoder_feed(frame_decoder *d, uint8_t byte, const uint8_t **payload, size_t *len);

#endif
#include "frame.h"

uint16_t crc16_ccitt(const uint8_t *data, size_t len)
{
    uint16_t crc = 0xFFFF;
    while (len--) {
        crc = (uint16_t)(crc ^ (*data++ << 8));
        for (int bit = 0; bit < 8; bit++)
            crc = (crc & 0x8000) ? (uint16_t)((crc << 1) ^ 0x1021) : (uint16_t)(crc << 1);
    }
    return crc;
}

static size_t put_escaped(uint8_t byte, uint8_t *out)
{
    if (byte == FRAME_END) {
        out[0] = FRAME_ESC;
        out[1] = FRAME_ESC_END;
        return 2;
    }
    if (byte == FRAME_ESC) {
        out[0] = FRAME_ESC;
        out[1] = FRAME_ESC_ESC;
        return 2;
    }
    out[0] = byte;
    return 1;
}

size_t frame_encode(const uint8_t *payload, size_t len, uint8_t *out, size_t out_cap)
{
    if (len == 0 || len > FRAME_MAX_PAYLOAD || out_cap < FRAME_ENCODED_MAX(len))
        return 0;

    uint16_t crc = crc16_ccitt(payload, len);
    size_t n = 0;
    out[n++] = FRAME_END;              /* a leading END flushes any line noise at the receiver */
    for (size_t i = 0; i < len; i++)
        n += put_escaped(payload[i], out + n);
    n += put_escaped((uint8_t)(crc >> 8), out + n);
    n += put_escaped((uint8_t)(crc & 0xFF), out + n);
    out[n++] = FRAME_END;
    return n;
}

void frame_decoder_init(frame_decoder *d)
{
    d->len = 0;
    d->escaped = false;
    d->broken = false;
    d->broken_reason = FRAME_NONE;
}

static void mark_broken(frame_decoder *d, frame_result why)
{
    if (!d->broken) {
        d->broken = true;
        d->broken_reason = why;
    }
}

frame_result frame_decoder_feed(frame_decoder *d, uint8_t byte, const uint8_t **payload, size_t *len)
{
    if (byte == FRAME_END) {
        frame_result result = FRAME_NONE;
        if (d->broken) {
            result = d->broken_reason;
        } else if (d->escaped) {
            result = FRAME_BAD_ESCAPE;
        } else if (d->len == 2) {
            result = FRAME_EMPTY;      /* never sent: a damaged byte became END */
        } else if (d->len > 2) {
            size_t n = d->len - 2;
            uint16_t sent = (uint16_t)((d->buf[n] << 8) | d->buf[n + 1]);
            if (crc16_ccitt(d->buf, n) == sent) {
                *payload = d->buf;
                *len = n;
                result = FRAME_OK;
            } else {
                result = FRAME_BAD_CRC;
            }
        } else if (d->len == 1) {
            result = FRAME_BAD_CRC;    /* one stray byte between two END bytes */
        }
        d->len = 0;                    /* an empty frame (END END) is just idle line */
        d->escaped = false;
        d->broken = false;
        return result;
    }

    if (d->broken)
        return FRAME_NONE;             /* skip to the next END */

    if (d->escaped) {
        d->escaped = false;
        if (byte == FRAME_ESC_END)
            byte = FRAME_END;
        else if (byte == FRAME_ESC_ESC)
            byte = FRAME_ESC;
        else {
            mark_broken(d, FRAME_BAD_ESCAPE);
            return FRAME_NONE;
        }
    } else if (byte == FRAME_ESC) {
        d->escaped = true;
        return FRAME_NONE;
    }

    if (d->len == sizeof d->buf) {
        mark_broken(d, FRAME_TOO_LONG);
        return FRAME_NONE;
    }
    d->buf[d->len++] = byte;
    return FRAME_NONE;
}

The CRC is computed with exclusive-or and shifts, one bit at a time (the operators in C article covers ^, << and &). The decoder takes one byte at a time, so it works no matter how the bytes are split across read() calls. Two design choices make it recover from noise: every frame starts with an END as well as ending with one, which flushes any garbage the receiver has collected, and a damaged frame is discarded whole, after which the decoder simply waits for the next END.

Output of frame_demo:

CRC-16/CCITT-FALSE of "123456789" = 0x29B1

payload:               48 69 C0 21 DB  (5 bytes)
on the wire:           C0 48 69 DB DC 21 DB DD C1 DA C0  (11 bytes)

clean frame                    -> OK "PING"
one bit flipped                -> bad CRC
one byte lost                  -> bad CRC
noise before the frame         -> bad CRC OK "PING"
two frames back to back        -> OK "ONE" OK "TWO"
closing END lost               -> OK "ONE" OK "TWO"
a data byte turned into END    -> empty

Reading the results line by line:

  • The CRC of the ASCII string “123456789” is 0x29B1, the published check value for CRC-16/CCITT-FALSE. Python’s binascii.crc_hqx(b"123456789", 0xFFFF) gives the same value, so this implementation agrees with an independent one.
  • The 5-byte payload became 11 bytes on the wire: two END bytes, two escape pairs and the CRC (bytes are listed in the ASCII table).
  • A flipped bit and a lost byte are both rejected by the CRC.
  • Noise before a frame becomes a rejected fragment, and the real frame behind it still arrives.
  • If the closing END is lost, the next frame’s opening END still separates the two messages. Without the leading END, “ONE” and “TWO” would merge into one damaged frame.
  • The last line shows a subtle failure covered in the next section.

How Reliable Is a CRC-16? An Experiment

A 16-bit CRC has 65,536 possible values, so random damage should slip through about once in 65,536 tries. Errors of a few bits are a different matter: CRC-16/CCITT is guaranteed to catch every 1-bit and 2-bit error, and every burst of up to 16 bits, in the data it covers, for messages far longer than the 256-byte limit here. This program damages encoded frames on purpose, feeds them to the decoder and counts what gets through:

Output of crc_experiment:

payloads: 1-64 random bytes; damage applied to the encoded bytes on the wire

damage                          trials  rejected    intact   WRONG MSG
1 bit flipped                   200000    200000         0           0
2 bits flipped                  200000    200000         0           0
burst of 2-16 bits              200000    200000         0           0
4 bytes replaced at random     2000000   1999971         0          29

expected WRONG MSG for random damage: about trials / 65536 = 30.5

The prediction held. No 1-bit, 2-bit or short-burst error produced a wrong message in 600,000 tries. With four bytes overwritten at random, 29 wrong messages got through in 2,000,000 tries, against a prediction of 30.5, about 1 in 69,000 against the expected 1 in 65,536.

The experiment also found a hole. Before the decoder rejected empty frames, one burst error out of 200,000 got through: in a 1-byte message (C0 FF FF 00 C0), the damage turned the last CRC byte into END. The receiver then saw FF FF as a complete frame with no payload, and 0xFFFF happens to be the CRC of zero bytes, so it passed. The CRC’s guarantees cover only the bytes it is computed over; when damage moves a frame boundary, the receiver checks a different frame. The fix is the FRAME_EMPTY rule, since a message always has at least one byte, which is the last line of the frame_demo output. A protocol that cannot afford even 1 wrong message in 65,000 needs a 32-bit CRC, a length field, or acknowledgements and retries on top.

The Chat Program

With the port and the framing in place, the chat program is short. One thread waits for frames and prints them, while the main thread reads lines from the keyboard and sends each one as a frame:

#define _POSIX_C_SOURCE 200809L
/* Two-way text chat over a serial port. Every line you type is sent as one
   framed message; every valid frame that arrives is printed.
   Usage: chat DEVICE [BAUD]   e.g.  chat /dev/ttyUSB0 115200   or   chat COM3 */
#include "frame.h"
#include "serial.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#else
#include <pthread.h>
#include <time.h>
#endif

static serial_port *port;

/* Runs on its own thread so that typing and receiving never block each other.
   Returns only when the port fails or the other end disconnects. */
static void receive_loop(void)
{
    frame_decoder dec;
    frame_decoder_init(&dec);
    unsigned long damaged = 0;
    uint8_t buf[256];

    long n;
    while ((n = serial_read(port, buf, sizeof buf, 200)) >= 0) {
        for (long i = 0; i < n; i++) {
            const uint8_t *msg = NULL;
            size_t len = 0;
            frame_result r = frame_decoder_feed(&dec, buf[i], &msg, &len);
            if (r == FRAME_OK) {
                printf("peer> %.*s\n", (int)len, (const char *)msg);
                fflush(stdout);
            } else if (r != FRAME_NONE) {
                fprintf(stderr, "(dropped a damaged frame; %lu so far)\n", ++damaged);
            }
        }
    }
    fprintf(stderr, "serial port closed or failed; nothing more will be received\n");
}

#ifdef _WIN32
static DWORD WINAPI reader(LPVOID arg)
{
    (void)arg;
    receive_loop();
    return 0;
}
#else
static void *reader(void *arg)
{
    (void)arg;
    receive_loop();
    return NULL;
}
#endif

int main(int argc, char **argv)
{
    if (argc < 2) {
        fprintf(stderr, "usage: %s DEVICE [BAUD]\n", argv[0]);
        return 2;
    }
    long baud = argc > 2 ? strtol(argv[2], NULL, 10) : 115200;

    char err[256];
    port = serial_open(argv[1], baud, err, sizeof err);
    if (port == NULL) {
        fprintf(stderr, "%s\n", err);
        return 1;
    }

#ifdef _WIN32
    if (CreateThread(NULL, 0, reader, NULL, 0, NULL) == NULL) {
#else
    pthread_t tid;
    if (pthread_create(&tid, NULL, reader, NULL) != 0) {
#endif
        fprintf(stderr, "cannot start the receive thread\n");
        return 1;
    }

    printf("connected to %s at %ld baud; type a line and press Enter\n", argv[1], baud);
    fflush(stdout);

    char line[FRAME_MAX_PAYLOAD + 1];
    uint8_t wire[FRAME_ENCODED_MAX(FRAME_MAX_PAYLOAD)];
    while (fgets(line, sizeof line, stdin) != NULL) {
        size_t len = strcspn(line, "\r\n");
        if (len == 0)
            continue;
        size_t n = frame_encode((const uint8_t *)line, len, wire, sizeof wire);
        if (n == 0 || !serial_write_all(port, wire, n)) {
            fprintf(stderr, "send failed\n");
            return 1;
        }
    }

    /* End of input: give replies already on the wire a moment to print. The
       receive thread is still using the port, so the OS closes it at exit. */
#ifdef _WIN32
    Sleep(300);
#else
    nanosleep(&(struct timespec){.tv_sec = 0, .tv_nsec = 300000000}, NULL);
#endif
    return 0;
}

A separate thread is the simplest portable way to wait for the keyboard and the serial port at the same time: on Linux the main loop could use poll() on both, but a Windows console handle cannot be waited on the same way as a COM port. Damaged frames are counted and reported on stderr rather than printed as garbage.

Two chats over a virtual cable

On Linux, socat creates two connected pseudo-terminals that behave like two serial ports joined by a cable:

socat -d -d pty,raw,echo=0,link=/tmp/ttyA pty,raw,echo=0,link=/tmp/ttyB
./chat /tmp/ttyA      # in a second terminal
./chat /tmp/ttyB      # in a third terminal

The repository’s test does exactly this, with a line typed on each side:

Output (each terminal’s screen):

--- terminal A
connected to /tmp/ttyA at 115200 baud; type a line and press Enter
peer> hi A, got it
--- terminal B
connected to /tmp/ttyB at 115200 baud; type a line and press Enter
peer> hello B, this is A

On real hardware, replace /tmp/ttyA with /dev/ttyUSB0 (or /dev/ttyS0 for a built-in port) and run chat COM3 on a Windows PC at the other end. On Linux your user usually needs to be in the dialout group to open a serial device. On Windows, a virtual null-modem driver such as com0com creates a connected pair of COM ports for testing without a cable.

Baud Rate: What the Numbers Mean in Bytes

With 8N1, each byte costs 10 bits on the wire: a start bit, 8 data bits and a stop bit. So the byte rate is the baud rate divided by 10:

Output of baud_table:

    baud      bytes/s        1 MiB raw     64-byte messages/s
    9600          960         1092.3 s                   14.1
   19200         1920          546.1 s                   28.2
   38400         3840          273.1 s                   56.5
   57600         5760          182.0 s                   84.7
  115200        11520           91.0 s                  169.4

At 9600 baud, a common default, a one-mebibyte file takes over 18 minutes. The last column counts 64-byte messages with this article’s framing (two END bytes and a 2-byte CRC; escapes add more for binary data). Both ends must be set to the same rate: a mismatch does not produce an error, only wrong bytes, which the CRC then rejects one frame after another.

Common Mistakes in Serial Port Code

Leaving the port in its default “cooked” mode

A terminal device’s default mode is built for keyboards: it buffers until Enter, turns carriage returns into newlines and treats some bytes as commands. This program writes seven bytes into a pseudo-terminal and reads them back, first with the default settings and then in raw mode:

/* What a terminal device in its default "cooked" mode does to binary data,
   compared with raw mode. Uses a pseudo-terminal, so no cable is needed.
   Linux and macOS only. */
#define _DEFAULT_SOURCE
#include <poll.h>
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#if defined(__APPLE__)
#include <util.h>
#else
#include <pty.h>
#endif

static void show(const char *label, int fd)
{
    unsigned char buf[64];
    struct pollfd pfd = {.fd = fd, .events = POLLIN};
    printf("%-10s", label);
    while (poll(&pfd, 1, 200) > 0) {
        ssize_t n = read(fd, buf, sizeof buf);
        if (n <= 0)
            break;
        printf(" [");
        for (ssize_t i = 0; i < n; i++)
            printf("%s%02X", i ? " " : "", buf[i]);
        printf("]");
    }
    printf("\n");
}

static void run(int raw)
{
    int master, slave;
    if (openpty(&master, &slave, NULL, NULL, NULL) != 0)
        return;
    if (raw) {
        struct termios t;
        tcgetattr(slave, &t);
        cfmakeraw(&t);
        tcsetattr(slave, TCSANOW, &t);
    }
    /* 'A', CR, 'B', XOFF, XON, 'C', LF */
    const unsigned char sent[] = {0x41, 0x0D, 0x42, 0x13, 0x11, 0x43, 0x0A};
    if (write(master, sent, sizeof sent) == (ssize_t)sizeof sent)
        show(raw ? "raw:" : "cooked:", slave);
    close(slave);
    close(master);
}

int main(void)
{
    printf("sent:      [41 0D 42 13 11 43 0A]\n");
    run(0);
    run(1);
    return 0;
}

Output:

sent:      [41 0D 42 13 11 43 0A]
cooked:    [41 0A] [42 43 0A]
raw:       [41 0D 42 13 11 43 0A]

In the default mode the carriage return (0D) arrived as a newline (0A), the XOFF and XON bytes (13 and 11) vanished because the driver treated them as flow-control commands, and the data came back as two reads split at the line ending. Raw mode delivered all seven bytes unchanged. Any program that sends binary data, or any byte above that list, needs raw mode.

Expecting one read to return one message

read() and ReadFile() return whatever bytes have arrived, which may be part of a message, several messages, or the end of one and the start of the next. Code that assumes “one read, one message” works in testing on a fast machine and fails on a slow link. Feed every byte through a decoder, as chat.c does, and let the framing decide where messages end.

Leaving flow control on with a three-wire cable

If hardware flow control (RTS/CTS) is enabled and the cable has no handshake wires, the sender waits forever for permission that never comes. Software flow control (XON/XOFF) is just as harmful for binary data, because 0x11 and 0x13 are ordinary bytes in a payload. Both are switched off explicitly in serial_posix.c and serial_win32.c.

Porting DOS-era serial code

Turbo C programs talked to the UART directly through bioscom() and port I/O at address 0x3F8:

/* DOS-era serial code, as written for Turbo C. It does not build with a modern
   compiler: the headers and the direct port access exist only under DOS. */
#include <bios.h>
#include <dos.h>

int main(void)
{
    bioscom(0, 0xE3, 0);          /* COM1: 9600 baud, 8 data bits, no parity, 1 stop */
    outportb(0x3F8, 'A');         /* write straight to the UART's I/O port */
    return 0;
}

Compiler output (GCC 13.3, and MinGW-w64 for Windows):

$ gcc -c dos_bioscom.c
dos_bioscom.c:3:10: fatal error: bios.h: No such file or directory
$ x86_64-w64-mingw32-gcc -c dos_bioscom.c
dos_bioscom.c:3:10: fatal error: bios.h: No such file or directory

The headers do not exist on any modern system, and adding them would not help: Windows and Linux do not allow ordinary programs to access hardware I/O ports, and a USB-to-serial adapter has no UART at 0x3F8 at all. Replace port I/O with the operating system’s serial API, as in the two serial_*.c files above.

When to Use TCP Instead

If both computers are on a network, TCP sockets are usually the better choice: the network stack already provides reliable, ordered delivery, retransmission and error checking, and it works across rooms and continents rather than the length of a cable. The MYCPLUS examples repository includes a TCP echo client and server in C. A serial link remains the right tool when there is no network: talking to a microcontroller, a lab instrument or a router’s console port, or connecting two machines with nothing but a cable.

Key Takeaways

  • Three wires are enough: transmit crossed to receive in both directions, plus ground. With no handshake wires, flow control must be off in software.
  • Configure the port in raw mode. The default terminal settings changed or removed three of seven bytes and split the data at the line ending.
  • The serial API is per-platform, the protocol is not. termios on Linux, CreateFile, DCB and COMMTIMEOUTS on Windows, behind one four-function interface.
  • Bytes are not messages. SLIP framing marks boundaries and lets the receiver recover after noise; a leading END keeps one damaged frame from swallowing the next.
  • A CRC-16 catches short errors completely and random damage about 65,535 times in 65,536. In 2,000,000 randomly damaged frames, 29 wrong messages got through against a predicted 30.5.
  • Moving a frame boundary defeats the CRC’s guarantees, which is why the decoder rejects empty frames.
  • DOS-era bioscom() code does not build anywhere today. Use the operating system’s serial API.

Conclusion

A serial link strips networking down to its parts. With nothing between two programs but a cable, every guarantee you rely on elsewhere, message boundaries, integrity, knowing when to stop waiting, becomes a few lines of code you write and can test. That is what makes it worth building once, even if your next project uses a socket.

The natural next steps are acknowledgements with retransmission, so a damaged message is sent again instead of dropped, and a length field or 32-bit CRC for links where one wrong message in 65,000 is too many. More C projects and tutorials are in the C programming section.

Source Code and Tests

serial-chat workflow status

All programs on this page are in the networking/serial-chat directory of the MYCPLUS C examples repository.

Build and test:

cmake -S . -B build
cmake --build build
ctest --test-dir build --output-on-failure

What the build checks. The code compiles with GCC and Clang under C11 and C17 with -Wall -Wextra -pedantic -Werror, with MSVC under /W4 /WX, and cross-compiles for Windows with MinGW-w64. The CRC matches the published check value and an independent table-driven implementation. Every payload length from 1 to 256 bytes survives an encode and decode round trip, including payloads made entirely of END or ESC bytes. Every possible single-bit error in a 32-byte frame is rejected, and oversized, empty and badly escaped frames are rejected with the decoder recovering at the next frame. On Linux, the serial code passes data each way through a pseudo-terminal, two chat processes exchange a line each way over a socat cable, every demo prints exactly the output shown here, and the DOS-era code still fails to build. The tests and demos run clean under AddressSanitizer and UndefinedBehaviorSanitizer.

The build does not test a physical serial port, a real Windows COM port, or baud-rate accuracy, which pseudo-terminals ignore.

What I Verified

Everything in the Ubuntu column was run for this article on Ubuntu 24.04 (x86-64, GCC 13.3, Clang 18, CMake 3.28, MinGW-w64 GCC 13). The WSL column comes from run_all.sh on Ubuntu 24.04 under WSL (GCC 13.3, CMake 3.28, socat), and the Windows column from run_all.ps1 on Windows 11 with MSVC.

CheckUbuntu 24.04WSL (Ubuntu 24.04)Windows 11
Builds with warnings as errors (GCC and Clang on Linux, MSVC /W4 /WX on Windows), C11 and C17GCC and Clang, C11 and C17: passed, zero warningsGCC 13.3, C11 and C17: passed, zero warnings (Clang not installed)MSVC /W4 /WX, C11 and C17: built
Tests (unit tests, byte-for-byte output checks; on Linux also the pseudo-terminal, chat and DOS-build tests)8 of 8 passed in all four configurations8 of 8 passed in C11 and C174 of 4 passed in C11 and C17 (unit test and three output checks; the pseudo-terminal tests are Linux-only)
AddressSanitizer and UndefinedBehaviorSanitizer over the tests and demosCleanCleanNot applicable
Windows code cross-compiled with MinGW-w64, warnings as errorsPassedNot runNot applicable
Two chat processes over a socat virtual cableEach received the other’s lineEach received the other’s line (part of the 8 tests)Not applicable
14 deliberate mistakes injected into the framing code to check the tests13 caught at first; the 14th (a buffer bound off by two) led to a new exact-size test, and all 14 are now caughtNot runNot run

Not covered: a physical serial cable or USB-to-serial adapter, a real or virtual (com0com) COM port on Windows, Clang on WSL, baud-rate accuracy and line noise on real hardware, macOS, and any timing.

Scroll to Top