Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the O_CLOEXEC when using std::ofstream

Tags:

c++

linux

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.

like image 909
Allan Avatar asked Nov 04 '22 19:11

Allan


1 Answers

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.

like image 138
cnicutar Avatar answered Nov 12 '22 14:11

cnicutar