我在串行端口/dev/ttyUSB0(使用 FTDI)上使用一个设备,我不想将任何文件描述符泄露给其他衍生进程,所以我在描述符上设置了 close-on-exec 标志。你能告诉我在打开时设置 O_CLOEXEC 有什么区别吗:
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
int fd, rc;
fd = open("/dev/ttyUSB1", O_RDWR | O_NOCTTY | O_CLOEXEC);
if(fd < 0)
{
perror("error open:");
exit(-1);
}
rc = close(fd);
if(rc != 0)
{
perror("error close:");
exit(-1);
}
return 0;
}
并使用 ioctl(fd, TIOCEXCL) 设置 close-on-exec:
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <sys/ioctl.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
int fd, rc;
fd = open("/dev/ttyUSB1", O_RDWR | O_NOCTTY);
if(fd < 0)
{
perror("error open:");
exit(-1);
}
rc = ioctl(fd, TIOCEXCL);
if(rc != 0)
{
perror("error ioctl:");
exit(-1);
}
rc = close(fd);
if(rc != 0)
{
perror("error close:");
exit(-1);
}
return 0;
}
最佳答案
TIOCEXCL
不 设置执行时关闭标志(即 FIOCLEX
,或者等效地,fcntl (fd, F_SETFD, FD_CLOEXEC)
).
回答你认为你在问的问题:
当您open()
时指定O_CLOEXEC
一个文件将在它返回之前设置close-on-exec 标志,为您节省另一个调用,重要的是,确保有没有竞争条件,另一个线程可能在 open()
之后但在随后的 fcntl()
之前调用 exec()
。
如果你真的需要在任何其他时间设置或取消设置标志(我从来不需要),你可以使用 fcntl F_SETFD
,传递 FD_CLOEXEC
或分别为 0
。
关于c - O_CLOEXEC 和 TIOCEXCL 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39848203/