FAQ 8.10 How do I read and write the serial port?

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

This message is one of several periodic postings to comp.lang.perl.misc
intended to make it easier for perl programmers to find answers to
common questions. The core of this message represents an excerpt
from the documentation provided with Perl.


8.10: How do I read and write the serial port?

    This depends on which operating system your program is running on. In
    the case of Unix, the serial ports will be accessible through files in
    /dev; on other systems, device names will doubtless differ. Several
    problem areas common to all device interaction are the following:

        Your system may use lockfiles to control multiple access. Make sure
        you follow the correct protocol. Unpredictable behavior can result
        from multiple processes reading from one device.

    open mode
        If you expect to use both read and write operations on the device,
        you'll have to open it for update (see "open" in perlfunc for
        details). You may wish to open it without running the risk of
        blocking by using sysopen() and "O_RDWR|O_NDELAY|O_NOCTTY" from the
        Fcntl module (part of the standard perl distribution). See "sysopen"
        in perlfunc for more on this approach.

    end of line
        Some devices will be expecting a "\r" at the end of each line rather
        than a "\n". In some ports of perl, "\r" and "\n" are different from
        their usual (Unix) ASCII values of "2" and "5". You may have
        to give the numeric values you want directly, using octal ("5"),
        hex ("0x0D"), or as a control-character specification ("\cM").

            print DEV "atv12";       # wrong, for some devices
            print DEV "atv15";       # right, for some devices

        Even though with normal text files a "\n" will do the trick, there
        is still no unified scheme for terminating a line that is portable
        between Unix, DOS/Win, and Macintosh, except to terminate *ALL* line
        ends with "52", and strip what you don't need from the output.
        This applies especially to socket I/O and autoflushing, discussed

    flushing output
        If you expect characters to get to your device when you print()
        them, you'll want to autoflush that filehandle. You can use select()
        and the $| variable to control autoflushing (see "$|" in perlvar and
        "select" in perlfunc, or perlfaq5, ``How do I flush/unbuffer an
        output filehandle? Why must I do this?''):

            $oldh = select(DEV);
            $| = 1;

        You'll also see code that does this without a temporary variable, as

            select((select(DEV), $| = 1)[0]);

        Or if you don't mind pulling in a few thousand lines of code just
        because you're afraid of a little $| variable:

            use IO::Handle;

        As mentioned in the previous item, this still doesn't work when
        using socket I/O between Unix and Macintosh. You'll need to hard
        code your line terminators, in that case.

    non-blocking input
        If you are doing a blocking read() or sysread(), you'll have to
        arrange for an alarm handler to provide a timeout (see "alarm" in
        perlfunc). If you have a non-blocking open, you'll likely have a
        non-blocking read, which means you may have to use a 4-arg select()
        to determine whether I/O is ready on that device (see "select" in

    While trying to read from his caller-id box, the notorious Jamie
    with sysread, sysopen, POSIX's tcgetattr business, and various other
    functions that go bump in the night, finally came up with this:

        sub open_modem {
            use IPC::Open2;
            my $stty = `/bin/stty -g`;
            open2( \*MODEM_IN, \*MODEM_OUT, "cu -l$modem_device -s2400 2>&1");
            # starting cu hoses /dev/tty's stty settings, even when it has
            # been opened on a pipe...
            system("/bin/stty $stty");
            $_ = <MODEM_IN>;
            if ( !m/^Connected/ ) {
                print STDERR "$0: cu printed `$_' instead of `Connected'\n";


Documents such as this have been called "Answers to Frequently
Asked Questions" or FAQ for short.  They represent an important
part of the Usenet tradition.  They serve to reduce the volume of
redundant traffic on a news group by providing quality answers to
questions that keep coming up.

If you are some how irritated by seeing these postings you are free
to ignore them or add the sender to your killfile.  If you find
errors or other problems with these postings please send corrections
or comments to the posting email address or to the maintainers as
directed in the perlfaq manual page.

Note that the FAQ text posted by this server may have been modified
from that distributed in the stable Perl release.  It may have been
edited to reflect the additions, changes and corrections provided
by respondents, reviewers, and critics to previous postings of
these FAQ. Complete text of these FAQ are available on request.

The perlfaq manual page contains the following copyright notice.


    Copyright (c) 1997-2002 Tom Christiansen and Nathan
    Torkington, and other contributors as noted. All rights

This posting is provided in the hope that it will be useful but
does not represent a commitment or contract of any kind on the part
of the contributers, authors or their agents.

Site Timeline