int serialDevice = open(“/ dev / ttyUSB0”,O_RDWR | O_NOCTTY);
除了@darune的回答和 O_NONBLOCK ,你可能会考虑 O_SYNC 太。另见 如何从C中的串口打开,读取和写入?
O_NONBLOCK
O_SYNC
您可能还会考虑使文件描述符独占,因此调制解调器管理器等其他程序无法打开设备 捣毁你的州 。独家是好的因为 O_RDWR 。另见 如何使/ dev / ttyACM0(和朋友)独占? 在Kernel Newbies邮件列表上。
O_RDWR
要使文件描述符独占,您需要使用 ioctl 和 TIOCEXCL 。 O_EXCL 没有按预期工作,因为它不适合使用字符设备(并且内核人员说 -ENOPATCH )。
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 就像是:
term_config
int serialDevice = open("/dev/ttyUSB0", ...); if (serialDevice == -1) { /* error */ } int result = term_config(serialDevice, B115200); if (result != 0) { /* error */ }
我相信如果设备繁忙等情况会发生这种情况。
你需要添加标志 的 O_NONBLOCK 强> :
O_NONBLOCK 使用O_RDONLY或O_WRONLY设置打开FIFO时: * 如果设置了O_NONBLOCK,则只读的open()应该无延迟地返回。如果没有,open()仅用于写入将返回错误 进程当前打开文件进行读取。 * 如果清除O_NONBLOCK,则只读的open()将阻塞调用线程,直到线程打开文件进行写入。开放() for writing-only将阻塞调用线程,直到线程打开 用于阅读的文件。 打开支持的块特殊或字符特殊文件时 非阻塞打开: * If O_NONBLOCK is set, the open() function shall return without blocking for the device to be ready or available. Subsequent behavior 该设备的设备是特定于设备的。 * 如果O_NONBLOCK清零,则open()函数将阻塞调用线程,直到设备准备好或之前可用 返回。 否则,未指定O_NONBLOCK的行为。
O_NONBLOCK 使用O_RDONLY或O_WRONLY设置打开FIFO时: * 如果设置了O_NONBLOCK,则只读的open()应该无延迟地返回。如果没有,open()仅用于写入将返回错误 进程当前打开文件进行读取。 * 如果清除O_NONBLOCK,则只读的open()将阻塞调用线程,直到线程打开文件进行写入。开放() for writing-only将阻塞调用线程,直到线程打开 用于阅读的文件。
打开支持的块特殊或字符特殊文件时 非阻塞打开:
* If O_NONBLOCK is set, the open() function shall return without blocking for the device to be ready or available. Subsequent behavior
该设备的设备是特定于设备的。 * 如果O_NONBLOCK清零,则open()函数将阻塞调用线程,直到设备准备好或之前可用 返回。
否则,未指定O_NONBLOCK的行为。