Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...