问题
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