AIX

AIX

Connect with fellow AIX users and experts to gain knowledge, share insights, and solve problems.

 View Only

Loopback test on serial port. Default termios config

  • 1.  Loopback test on serial port. Default termios config

    Posted Mon August 13, 2012 11:44 AM

    Originally posted by: susan12


    I am writing a code to identify serial ports with a loopback device. I fork 2 processes, one to write "Hello\n" and the other one to read and compare with "Hello". If everything completes properly within 1 second (alarm) then it's a loopback device. Otherwise it's not. I use it to associate port numbers with cables.

    The problem is how to configure the serial line properly. With default parameters it works fine. However, if another program modified it
    (e.g. the programs I use to read from serial sensors) without restoring the defaults, it doesn't work any more. So how to restore the default settings? Or what are the settings I need for this test?

    Here is how I currently do it. It seems to work ok in most cases but I'd like to be sure. I removed all error checking to make the code
    more readable.

    int fd = -1;
    int oldflags;
    struct termios tty;

    fd = open(device, O_RDWR | O_NOCTTY | O_NONBLOCK);
    oldflags = fcntl(fd, F_GETFL, 0);
    fcntl(fd, F_SETFL, oldflags & ~O_NONBLOCK);
    tcflush(fd, TCIOFLUSH);

    memset(&tty,0,sizeof(struct termios));
    tty.c_iflag = ICRNL | IXON;
    tty.c_cflag = CS8 | CREAD | HUPCL | CLOCAL;
    tty.c_lflag = ICANON | OPOST | ISIG | IEXTEN;
    tty.c_lflag |= ECHO | ECHOE | ECHOK | ECHOCTL | ECHOKE;
    tty.c_oflag = OPOST | ONLCR | NL0 | CR0 | TAB0 | BS0 | VT0 | FF0;
    tty.c_ccVMIN = 1;
    tty.c_ccVTIME = 0;
    tty.c_line = N_TTY;

    cfsetospeed(&tty, B9600);
    cfsetispeed(&tty, B9600);

    tcsetattr(fd, TCSADRAIN, &tty);
    I got all these setting by looking at "stty -F /dev/ttyS0 -a" just after booting.