为什么在串行端口编程中使用fcntl(fd,F_SETFL,0) [英] Why fcntl(fd, F_SETFL, 0) use in serial port programming
问题描述
我正在Linux中开始串行端口编程.在阅读了网上的几个示例后,我不了解fcntl(fd, F_SETFL, 0)
的确切效果吗?它正在清除位,但是它会影响哪些标志?它设置和/或清除了什么?
I am starting serial port programming in Linux. After reading several examples on the web, I don't understand exact effect of fcntl(fd, F_SETFL, 0)
? It is clearing bits, but what flags does it affect? What does it set and or clear?
推荐答案
一个接一个
1)使用了函数调用
fcntl()
-它对传入参数中的文件描述符执行操作.
fcntl()
- It perform the operation on file descriptor passed in argument.
2)通话中的第二个参数
2) 2nd argument in call
F_SETFL (int)
将文件状态标志设置为arg指定的值.档案存取 模式(O_RDONLY,O_WRONLY,O_RDWR)和文件创建标志(即 arg中的O_CREAT,O_EXCL,O_NOCTTY,O_TRUNC)将被忽略.在Linux上, 命令只能更改O_APPEND,O_ASYNC,O_DIRECT,O_NOATIME, 和O_NONBLOCK标志.
Set the file status flags to the value specified by arg. File access mode (O_RDONLY, O_WRONLY, O_RDWR) and file creation flags (i.e., O_CREAT, O_EXCL, O_NOCTTY, O_TRUNC) in arg are ignored. On Linux this command can change only the O_APPEND, O_ASYNC, O_DIRECT, O_NOATIME, and O_NONBLOCK flags.
3)通话中的第三个参数
3) 3rd argument in call
It is 0 means, It set file status flag to zero. As Jean-Baptiste Yunès said in comment.
文件访问模式和文件创建标志将被忽略.这个命令 重置所有其他标志:无附加,无异步,无直接,无时间和 没有畅通无阻
file access mode and file creation flags are ignored. This command reset every other flags: no append, no async, no direct, no atime, and no nonblocking
所以最后
So finally
fcntl(fd, F_SETFL, 0)
此调用会将打开的文件描述符的file status
标志设置为值0.
This call will set opened file desciptor's file status
flag to value 0.
但是理想情况下,我们不应该更改文件状态标志.
最好的方法是先使用F_GETFL
获取当前文件状态标志,然后在其中更改所需的位.
参见示例:
But idealy this way we should not change file status flag.
Best way is to first get the current file status flag using F_GETFL
and then just change required bit in that.
See example:
如果要修改文件状态标志,则应使用F_GETFL获取当前标志并修改该值.不要以为这里列出的标志是唯一实现的标志;您的程序可能会从现在开始运行数年,然后可能会存在更多标志.例如,这是一个无需更改任何其他标志即可设置或清除标志O_NONBLOCK的函数:
If you want to modify the file status flags, you should get the current flags with F_GETFL and modify the value. Don’t assume that the flags listed here are the only ones that are implemented; your program may be run years from now and more flags may exist then. For example, here is a function to set or clear the flag O_NONBLOCK without altering any other flags:
/* Set the O_NONBLOCK flag of desc if value is nonzero,
or clear the flag if value is 0.
Return 0 on success, or -1 on error with errno set. */
int
set_nonblock_flag (int desc, int value)
{
int oldflags = fcntl (desc, F_GETFL, 0);
/* If reading the flags failed, return error indication now. */
if (oldflags == -1)
return -1;
/* Set just the flag we want to set. */
if (value != 0)
oldflags |= O_NONBLOCK;
else
oldflags &= ~O_NONBLOCK;
/* Store modified flag word in the descriptor. */
return fcntl (desc, F_SETFL, oldflags);
}
这篇关于为什么在串行端口编程中使用fcntl(fd,F_SETFL,0)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!