我在串口/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
不是“exec关闭”。它将终端设置为“独占”模式。它与防止泄漏文件描述符无关。您可能在考虑使用fcntl(fd, F_SETFD, old_flags | FD_CLOEXEC)
代替。 - user824425