int serialDevice = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY);
In addition to @darune's answer and O_NONBLOCK
, you might consider O_SYNC
too. Also see How to open, read, and write from serial port in C?
You might also consider making the file descriptor exclusive so another program like Modem Manager does not open the device and muck with your state. Exclusive is fine because of O_RDWR
. Also see How to make /dev/ttyACM0 (and friends) exclusive? on the Kernel Newbies mailing list.
To make the file descriptor exclusive you need to use ioctl
and TIOCEXCL
. O_EXCL
does not work as expected because it is not honored for character devices (and the kernel folks say -ENOPATCH
).
int term_config(int fd, int speed)
{
struct termios tty;
memset(&tty, 0, sizeof(tty));
if (tcgetattr(fd, &tty) != 0) {
log_error("term_config: tcgetattr: %s\n", strerror(errno));
return -1;
}
cfmakeraw(&tty);
tty.c_cflag |= CLOCAL; /* ignore status lines */
tty.c_cflag |= CRTSCTS; /* hardware flow control */
cfsetospeed(&tty,(speed_t)speed);
cfsetispeed(&tty,(speed_t)speed);
if (tcsetattr(fd, TCSANOW, &tty) != 0) {
log_error("term_config: tcsetattr: %s\n", strerror(errno));
return -1;
}
if (ioctl(fd, TIOCEXCL, NULL) != 0) {
log_error("term_config: ioctl_tty: %s\n", strerror(errno));
return -1;
}
return 0;
}
You would call term_config
something like:
int serialDevice = open("/dev/ttyUSB0", ...);
if (serialDevice == -1) { /* error */ }
int result = term_config(serialDevice, B115200);
if (result != 0) { /* error */ }