int serialDevice = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY);
除了@darune 的回答和O_NONBLOCK,你也可以考虑O_SYNC。另见How to open, read, and write from serial port in C?
您也可以考虑将文件描述符设为独占,这样调制解调器管理器等其他程序就不会打开设备和muck with your state。由于O_RDWR,独占很好。另请参阅内核新手邮件列表中的How to make /dev/ttyACM0 (and friends) exclusive?。
要使文件描述符独占,您需要使用ioctl 和TIOCEXCL。 O_EXCL 不能按预期工作,因为它不适用于字符设备(内核人员说 -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;
}
你会打电话给term_config,比如:
int serialDevice = open("/dev/ttyUSB0", ...);
if (serialDevice == -1) { /* error */ }
int result = term_config(serialDevice, B115200);
if (result != 0) { /* error */ }