c - O_CLOEXEC 和 TIOCEXCL 之间的区别

标签 c linux

我在串行端口/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/

相关文章:

c - 如何通过在 printf ("%ex",test()) 中定义新标识符来启用 printf() 函数以在 C 中打印 boolean 类型?

c++ - 了解 C 和 C++ 中的暂定定义

Linux Uart 驱动修改

c - C在JNI中的实现,语法改变

python - 为什么我的缓冲区溢出漏洞只会打开用户 shell 而不是 root shell?

c - 如何手动替换 C 中字符串中的最后一次出现?

linux - Linux部署中的File.separator

linux - Nose 测试不同 Python 版本的执行?

linux - OSX 中的网络浏览器能否使用由同一台机器上运行的虚拟机提供的浏览器应用程序?

linux - 如何选择最高质量的照片版本?