开发者

How to set the O_CLOEXEC when using std::ofstream

开发者 https://www.devze.com 2023-03-14 03:32 出处:网络
What is the c++ (std::ofstream) equivalent of: int fd = open(fn,开发者_运维知识库O_WRONLY|O_NDELAY|O_APPEND|O_CREAT|O_CLOEXEC,0600);

What is the c++ (std::ofstream) equivalent of:

int fd = open(fn,开发者_运维知识库O_WRONLY|O_NDELAY|O_APPEND|O_CREAT|O_CLOEXEC,0600);

The application I would like to use this for will only run on newer versions of linux, therefor portability is not an issue.


There is (likely) no portable way to do this. There are at least two options.

First option, obtain fd / attach fd

  • Obtain the file descriptor of the ofstream
  • Attach a file descriptor to the ofstream

There are lots of examples of "attaching a file descriptor", "getting file descriptor from fstream" etc. If you can find one that works, you're all set.

If you can do the first one, you can do a fcntl on the file.

/* not checking return values since I am lazy; *you* should check them */
flags = fcntl(fd, F_GETFD);
flags |= FD_CLOEXEC;
fcntl(fd, F_SETFD, flags)

If you can do the second one, you can simply obtain your descriptor via open and attach it.

Second option, obtain all open fds and set FD_CLOEXEC on them

This is less clean (but more likely to work). Open all the fstreams you don't want your children to inherit. Go to /proc/self/fd. For each fd set the FC_CLOEXEC flag.

0

精彩评论

暂无评论...
验证码 换一张
取 消