Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

macOS blocking serial I/O

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...