在Linux中打开文件时应何时使用O_CLOEXEC? [英] When should I use O_CLOEXEC when I open file in Linux?

查看:94
本文介绍了在Linux中打开文件时应何时使用O_CLOEXEC?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的进程分叉几次,并且每次孩子执行时-意味着我希望它运行其他程序.

My process forks several times, and each time the child will exec - means I want it to run some other program.

在主过程中,我使用 open() syscall打开文件描述符.

In the main process I open a file descriptor with the open() syscall.

给它一个标志 O_CLOEXEC 是否正确,以便我使用 exec()运行的新程序没有fd资源?

Would it be correct to give it a flag O_CLOEXEC so the new program that I run with exec() wouldn't has the fd resource?

推荐答案

是的,除非您需要执行的程序才能访问该文件描述符.您还可以在调用exec之前在子进程中手动关闭文件描述符,但这更容易出错.

Yes, unless you need the program you exec to have access to that file descriptor. You can also close the file descriptor manually in the child process before calling exec, but that's more error prone.

这篇关于在Linux中打开文件时应何时使用O_CLOEXEC?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆