macOS blocking serial I/O

倾然丶 夕夏残阳落幕 提交于 2019-12-25 18:37:11

问题


I'm writing a tool as part of a test suite, which needs to talk over a serial port to some hardware so that the code being tested sees the environment change.

So, I do this:

open("/dev/tty.usbmodem14141", O_RDWR | O_NOCTTY);

only it hangs there. If I replace that call with

open("/dev/tty.usbmodem14141", O_RDWR | O_NOCTTY | O_NONBLOCK);

then it works -- but I would prefer not to have to fiddle with select() and friends, or write a busy-loop poll, just so I can read from the serial port; that's what blocking I/O is for.

Do I need to do anything special for this to work?


回答1:


When you have opened the serial terminal in nonblocking mode, you can then clear the file status flag to perform I/O in blocking mode.

To clear the nonblocking status flag you can use fcntl(), e.g.:

int flags;

flags = fcntl(fd, F_GETFL);
flags &= ~O_NONBLOCK;
fcntl(fd, F_SETFL, flags);

Since the Linux version of F_SETFL can change only the O_APPEND, O_ASYNC, O_DIRECT, O_NOATIME, and O_NONBLOCK flags, common practice is to simplify the code down to just

fcntl(fd, F_SETFL, 0);

(Yes, the single-liner does not have the same degree of portability as advocated in Setting Terminal Modes Properly.)



来源:https://stackoverflow.com/questions/56169472/macos-blocking-serial-i-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!