Linux bulk data transfer over serial device

Tue, Dec 13, 2016

I recently needed to use a serial connection for bulk data transfer. Now, the serial interface of Linux (and other posixy OSes) has a lot of configurability built in so that it can work with all sorts of serial interfaces and terminals. The terminal control codes are sent inline in the data stream, and therefore Linux will interpret the stream and act accordingly, for example by inserting parity bits for error detection, or by changing all characters to upper case.

In my case I had a virtio-serial connection between VMs, so I did not need any of these features. Instead, I wanted the serial device to just copy the data from one side to the other without interpreting it – raw data transmission.

So the challenge is to configure the serial port for raw data transmission

In C this is quite easy actually:

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

#include <stdio.h>

int main()
{
    struct termios t;
    int fd;

    fd = open("/dev/hvc0", NULL);
    if (fd < 0) {
        printf("Could not open terminal file.\n");
        return 1;
    }

    // configure serial line
    assert(tcgetattr(fd, &t) == 0);
    cfmakeraw(&t);
    tcflush(fd, TCIFLUSH);
    assert(tcsetattr(fd, TCSANOW, &t) == 0);

    // write something
    ssize_t b = write(fd, "hello world", sizeof("hello world"));
    if (b < sizeof("hello world")) {
        printf("Write failed.\n");
        return 1;
    }

    // read something
    char buf[10];
    b = 0;
    while (b) {
        b = read(fd, buf, sizeof(buf));
        printf("Read: %*s\n", b, buf);
    }

    close(fd);

    return 0;
}

In a shellscript stty will do the job:

#!/bin/sh

# use /dev/hvc0 for stdin and stdout
exec < /dev/hvc0
exec > /dev/hvc0

# configure tty
stty raw -echo

# write sth.
echo 'hello world'

# read and print
while read -r line;
do
    echo $line;
done
Tags: linux

Prev: Matias Secure Pro Wireless Keyboard Personal Review Next: HOWTO fix deja-dup --backup error Permission denied
Home | Impressum