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

enum { buf_size = 4096 };

static void die(const char *msg, int num)
{
    perror(msg);
    exit(num);
}

int main(int argc, char **argv)
{
    int fd, code, count;
    const char *dev, *msg;
    char buf[buf_size];
    char read_write;

    if (argc != 4) {
        fprintf(stderr, "Usage: %s </dev/pts/x> <r/w> <message>\n", argv[0]);
        return 2;
    }
    dev = argv[1];
    read_write = argv[2][0];
    msg = argv[3];

    switch (read_write) {
        case 'r': fd = open(dev, O_RDONLY); break;
        case 'w': fd = open(dev, O_WRONLY, 0666); break;
    }
    if (fd == -1)
        die("open", 1);

    switch (read_write) {
        case 'r':
            count = read(fd, buf, buf_size);
            write(1, buf, count);
            break;
        case 'w':
            code = write(fd, msg, strlen(msg));
            if (code == -1)
                die("write", 2);
            break;
    }

    code = close(fd);
    if (code)
        die("open", 3);

    return 0;
}
