C语言 FD_CLOEXEC fcntl() 标志有什么作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6125068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 08:45:33  来源:igfitidea点击:

What does the FD_CLOEXEC fcntl() flag do?

c

提问by compile-fan

Like so:

像这样:

if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
...

Though I've read man fcntl, I can't figure out what it does.

虽然我读过man fcntl,但我无法弄清楚它的作用。

采纳答案by R.. GitHub STOP HELPING ICE

It sets the close-on-execflag for the file descriptor, which causes the file descriptor to be automatically (and atomically) closed when any of the exec-family functions succeed.

它为文件描述符设置close-on-exec标志,这会导致文件描述符在任何exec-family 函数成功时自动(和原子地)关闭。

It also tests the return value to see if the operation failed, which is rather useless if the file descriptor is valid, since there is no condition under which this operation should fail on a valid file descriptor.

它还测试返回值以查看操作是否失败,如果文件描述符有效,这将毫无用处,因为没有条件在有效的文件描述符上此操作应该失败。

回答by geekosaur

It marks the file descriptor so that it will be close()d automatically when the process or any children it fork()s calls one of the exec*()family of functions. This is useful to keep from leaking your file descriptors to random programs run by e.g. system().

它标记文件描述符,以便close()在进程或其任何子进程fork()调用该exec*()系列函数之一时自动将其删除。这对于防止将文件描述符泄漏到由例如system().